我的任务是创建一个方法,该方法将接受用户输入的3位数int并输出其倒数(123-321)。我不允许将int转换为字符串,否则会丢失点,也不允许在main以外的任何位置进行打印。
public class Lab01
{
public int sumTheDigits(int num)
{
int sum = 0;
while(num > 0)
{
sum = sum + num % 10;
num = num/10;
}
return sum;
}
public int reverseTheOrder(int reverse)
{
return reverse;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Lab01 lab = new Lab01();
System.out.println("Enter a three digit number: ");
int theNum = input.nextInt();
int theSum = lab.sumTheDigits(theNum);
int theReverse = lab.reverseTheOrder(theSum);
System.out.println("The sum of the digits of " + theNum + " is " + theSum);
您可以使用以下方法来计算数字的倒数。
public int reverseTheOrder(int reverse){
int result = 0;
while(reverse != 0){
int rem = reverse%10;
result = (result *10) + rem;
reverse /= 10;
}
return result;
}