如何反转用户接受的Java中的数字并添加两个反转的数字

时间:2015-09-21 13:15:53

标签: java

我编写了一个代码来反转java中的数字。但它只占用一个角色/显示它。

import java.util.Scanner;
class HelloWorld
{
public static void main(String args[])
{
int n,n1, reverse = 0,rev = 0;
System.out.println("Enter the number to reverse");

Scanner scanner = new Scanner(System.in);

System.err.println("Please enter first number to reverse : ");
int number = scanner.nextInt();

System.out.println("Enter second number to reverse :");
int num = scanner.nextInt();

if( number >0)
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;

 if(num>0)
  {
    rev = rev * 10;
    rev = rev + num%10;
    num = num/10;
  }

 }
 System.out.println("Reverse of entered number is "+reverse);
 System.out.println("Reverse of entered number is "+rev);
}
}

输入1 -65 输出显示 - 5 输入2 -34 输出显示 - 4

我必须反转用户的输入并添加两个输入的反向。

3 个答案:

答案 0 :(得分:2)

1)使用while而不是if。

2)如果你在while循环中计算第二个数字的反向,找到第一个数字的反转,如果第二个数字更长,那么它将不起作用。单独执行

while(number > 0)
{
    reverse = reverse * 10;
    reverse = reverse + number%10;
    number = number/10;
}
while(num > 0)
{
    rev = rev * 10;
    rev = rev + num%10;
    num = num/10;
}

答案 1 :(得分:0)

你可以这样做,正如@ user7指出的那样,使用while循环,而不是if循环

while( number >0)
{
    reverse1 = reverse1 * 10;
    reverse1 = reverse1 + number%10;
    number = number/10;
}
while( number2 >0)
{
    reverse2 = reverse2 * 10;
    reverse2 = reverse2 + num%10;
    num = num/10;
}

System.out.println(reverse1+reverse2);

现在有多个号码

int[] numbers= numbers to be reversed;
reverseSum=0;
for(int i=0;i<numbers.length;i++){
    reverseSum+= reverse(numbers[i]);
}
...

public int reverse(int number){
     while( number >0)
    {
        reverse = reverse * 10;
        reverse = reverse + number%10;
        number = number/10;
    }
    return reverse;
}

希望这有帮助!

祝你好运!

答案 2 :(得分:0)

您可以

import java.util.Scanner;
import java.lang.StringBuilder
class HelloWorld
 {
   public static void main(String args[])
   {
  int n,n1, reverse = 0,rev = 0;
  String string1,string2;
  System.out.println("Enter the number to reverse");

  Scanner scanner = new Scanner(System.in);

  System.err.println("Please enter first number to reverse : ");
  int number = scanner.nextInt();

  System.out.println("Enter second number to reverse :");
  int num = scanner.nextInt();

  StringBuilder str1 =new StringBuilder(number+"");
  StringBuilder str2 =new StringBuilder(num+"");

   string1=str1.reverse().toString();
   string2=str2.reverse().toString();


 }
 System.out.println("Reverse of entered number is "+string1);
 System.out.println("Reverse of entered number is "+string2);
 }
}

最后,您可以使用Integer.ParseInt方法将反转字符串转换为整数并添加