[英]Trying to reverse 123 _> 321 using int Java
我的任務是創建一個方法,該方法將從用戶那里獲取 3 位數字輸入並反轉其順序,然后以新的順序將其返回,而不將任何內容轉換為字符串,所有內容都保留為 int。 我無法弄清楚如何在不將值相加的情況下返回新數字(第一第二第三);
public class Lab01
{
public int sumTheDigits(int num)
{
int one;
int two;
int three;
one = num % 10;
two = (num/10) % 10;
three = num / 100;
return one + two + three;
}
public int reverseTheOrder(int num)
{
int first;
int second;
int third;
third = num / 100;
second = (num/10) % 10;
first = num % 10;
return ?;
}
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);
System.,out.println(theNum + " reversed is " + theReverse);
}
}
您可以嘗試以下任何數字長度
public static void main(String args[]) {
int num = 0;
int reversenum = 0;
System.out.println("Enter number: ");
Scanner in = new Scanner(System.in);
num = in.nextInt();
while (num != 0) {
reversenum = reversenum * 10;
reversenum = reversenum + num % 10;
num = num / 10;
}
System.out.println("Reverse number is: " + reversenum);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.