Java reverse an int value without using array

2019-01-02 18:03发布

Can anyone explain to me how to reverse an integer without using array or String. I got this code from online, but not really understand why + input % 10 and divide again.

while (input != 0) {
    reversedNum = reversedNum * 10 + input % 10;
    input = input / 10;   
}

And how to do use this sample code to reverse only odd number. Example I got this input 12345, then it will reverse the odd number to output 531.

29条回答
姐姐魅力值爆表
2楼-- · 2019-01-02 18:39

123 maps to 321, which can be calculated as 3*(10^2)+2*(10^1)+1 Two functions are used to calculate (10^N). The first function calculates the value of N. The second function calculates the value for ten to power N.

Function<Integer, Integer> powerN = x -> Double.valueOf(Math.log10(x)).intValue();
Function<Integer, Integer> ten2powerN = y -> Double.valueOf(Math.pow(10, y)).intValue();

// 123 => 321= 3*10^2 + 2*10 + 1
public int reverse(int number) {
    if (number < 10) {
        return number;
    } else {
        return (number % 10) * powerN.andThen(ten2powerN).apply(number) + reverse(number / 10);
    }
}
查看更多
栀子花@的思念
3楼-- · 2019-01-02 18:41

Just to add on, in the hope to make the solution more complete.

The logic by @sheki already gave the correct way of reversing an integer in Java. If you assume the input you use and the result you get always fall within the range [-2147483648, 2147483647], you should be safe to use the codes by @sheki. Otherwise, it'll be a good practice to catch the exception.

Java 8 introduced the methods addExact, subtractExact, multiplyExact and toIntExact. These methods will throw ArithmeticException upon overflow. Therefore, you can use the below implementation to implement a clean and a bit safer method to reverse an integer. Generally we can use the mentioned methods to do mathematical calculation and explicitly handle overflow issue, which is always recommended if there's a possibility of overflow in the actual usage.

public int reverse(int x) {
    int result = 0;

    while (x != 0){
        try {
            result = Math.multiplyExact(result, 10);
            result = Math.addExact(result, x % 10);
            x /= 10;
        } catch (ArithmeticException e) {
            result = 0; // Exception handling
            break;
        }
    }

    return result;
}
查看更多
唯独是你
4楼-- · 2019-01-02 18:44

See to get the last digit of any number we divide it by 10 so we either achieve zero or a digit which is placed on last and when we do this continuously we get the whole number as an integer reversed.

    int number=8989,last_num,sum=0;
    while(number>0){
    last_num=number%10; // this will give 8989%10=9
    number/=10;     // now we have 9 in last and now num/ by 10= 898
    sum=sum*10+last_number; //  sum=0*10+9=9;
    }
    // last_num=9.   number= 898. sum=9
    // last_num=8.   number =89.  sum=9*10+8= 98
   // last_num=9.   number=8.    sum=98*10+9=989
   // last_num=8.   number=0.    sum=989*10+8=9898
  // hence completed
   System.out.println("Reverse is"+sum);
查看更多
几人难应
5楼-- · 2019-01-02 18:44
public static void main(String args[]) {
    int n = 0, res = 0, n1 = 0, rev = 0;
    int sum = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please Enter No.: ");
    n1 = scan.nextInt(); // String s1=String.valueOf(n1);
    int len = (n1 == 0) ? 1 : (int) Math.log10(n1) + 1;
    while (n1 > 0) {
        rev = res * ((int) Math.pow(10, len));
        res = n1 % 10;
        n1 = n1 / 10;
        // sum+=res; //sum=sum+res;
        sum += rev;
        len--;
    }
    // System.out.println("sum No: " + sum);
    System.out.println("sum No: " + (sum + res));
}

This will return reverse of integer

查看更多
旧人旧事旧时光
6楼-- · 2019-01-02 18:44

It's good that you wrote out your original code. I have another way to code this concept of reversing an integer. I'm only going to allow up to 10 digits. However, I am going to make the assumption that the user will not enter a zero.

if((inputNum <= 999999999)&&(inputNum > 0 ))
{
   System.out.print("Your number reversed is: ");

   do
   {
      endInt = inputNum % 10; //to get the last digit of the number
      inputNum /= 10;
      system.out.print(endInt);
   }
   While(inputNum != 0);
 System.out.println("");

}
 else
   System.out.println("You used an incorrect number of integers.\n");

System.out.println("Program end");
查看更多
公子世无双
7楼-- · 2019-01-02 18:45

It is an outdated question, but as a reference for others First of all reversedNum must be initialized to 0;

input%10 is used to get the last digit from input

input/10 is used to get rid of the last digit from input, which you have added to the reversedNum

Let's say input was 135

135 % 10 is 5 Since reversed number was initialized to 0 now reversedNum will be 5

Then we get rid of 5 by dividing 135 by 10

Now input will be just 13

Your code loops through these steps until all digits are added to the reversed number or in other words untill input becomes 0.

查看更多
登录 后发表回答