Java 在不使用数组的情况下反转 int 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3806126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 05:19:22  来源:igfitidea点击:

Java reverse an int value without using array

javaintegerreverse

提问by user236501

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.

谁能向我解释如何在不使用数组或字符串的情况下反转整数。我从网上得到了这段代码,但不太明白为什么 + 输入 % 10 并再次除法。

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.

以及如何使用此示例代码仅反转奇数。例子我得到这个输入12345,然后它将奇数反转输出531。

采纳答案by sheki

I am not clear about your Odd number. The way this code works is (it is not a Java specific algorithm) Eg. input =2345 first time in the while loop rev=5 input=234 second time rev=5*10+4=54 input=23 third time rev=54*10+3 input=2 fourth time rev=543*10+2 input=0

我不清楚你的奇数。这段代码的工作方式是(它不是特定于 Java 的算法)例如。在while循环中第一次输入=2345 rev=5 input=234 第二次rev=5*10+4=54 input=23 第三次rev=54*10+3 input=2 第四次rev=543*10+2输入=0

So the reversed number is 5432. If you just want only the odd numbers in the reversed number then. The code is:

所以倒数是5432。如​​果你只想要倒数中的奇数那么。代码是:

while (input != 0) {    
    last_digit = input % 10;
    if (last_digit % 2 != 0) {     
        reversedNum = reversedNum * 10 + last_digit;

    }
    input = input / 10; 
}

回答by Eric Leschinski

Java reverse an int value - Principles

Java 反转一个 int 值 - 原理

  1. Modding (%) the input int by 10 will extract off the rightmost digit. example: (1234 % 10) = 4

  2. Multiplying an integer by 10 will "push it left" exposing a zero to the right of that number, example: (5 * 10) = 50

  3. Dividing an integer by 10 will remove the rightmost digit. (75 / 10) = 7

  1. 将输入 int 修改 (%) 10 将提取最右边的数字。示例:(1234 % 10) = 4

  2. 将整数乘以 10 将“向左推”在该数字的右侧暴露一个零,例如:(5 * 10) = 50

  3. 将整数除以 10 将删除最右边的数字。(75 / 10) = 7

Java reverse an int value - Pseudocode:

Java 反转 int 值 - 伪代码:

a. Extract off the rightmost digit of your input number. (1234 % 10) = 4

一种。提取输入号码的最右边数字。(1234 % 10) = 4

b. Take that digit (4) and add it into a new reversedNum.

湾 取那个数字 (4) 并将其添加到新的 reversedNum 中。

c. Multiply reversedNum by 10 (4 * 10) = 40, this exposes a zero to the right of your (4).

C。将 reversedNum 乘以 10 (4 * 10) = 40,这会在 (4) 的右侧暴露一个零。

d. Divide the input by 10, (removing the rightmost digit). (1234 / 10) = 123

d. 将输入除以 10,(去掉最右边的数字)。(1234 / 10) = 123

e. Repeat at step a with 123

e. 用 123 在步骤 a 重复

Java reverse an int value - Working code

Java 反转 int 值 - 工作代码

public int reverseInt(int input) {
    long reversedNum = 0;
    long input_long = input;

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

    if (reversedNum > Integer.MAX_VALUE || reversedNum < Integer.MIN_VALUE) {
        throw new IllegalArgumentException();
    }
    return (int) reversedNum;
}

You will never do anything like this in the real work-world. However, the process by which you use to solve it without help is what separates people who can solve problems from the ones who want to, but can't unless they are spoon fed by nice people on the blogoblags.

在真实的工作世界中,你永远不会做这样的事情。然而,你用来在没有帮助的情况下解决问题的过程将能够解决问题的人和想要解决问题的人区分开来,除非他们被博客上的好人用勺子喂食。

回答by Solbet

int convert (int n)
{
        long val = 0;

        if(n==0)
            return 0;

        for(int i = 1; n > exponent(10,  (i-1)); i++)
        {
            int mod = n%( (exponent(10, i))) ;
            int index = mod / (exponent(10, i-1));

            val *= 10;
            val += index;
        }

        if (val < Integer.MIN_VALUE || val > Integer.MAX_VALUE) 
        {
            throw new IllegalArgumentException
                (val + " cannot be cast to int without changing its value.");
        }
        return (int) val;

    }


static int exponent(int m, int n)
    {
        if(n < 0) 
            return 0;
        if(0 == n) 
            return 1;

        return (m * exponent(m, n-1));

    }

回答by Ahmed Hamdy

while (num != 0) {
    rev = rev * 10 + num % 10;
    num /= 10;
}

That is the solution I used for this problem, and it works fine. More details:

这是我用于解决此问题的解决方案,并且效果很好。更多细节:

num % 10

This statement will get you the last digit from the original number.

此语句将为您提供原始号码的最后一位数字。

num /= 10

This statement will eliminate the last digit from the original number, and hence we are sure that while loop will terminate.

该语句将从原始数字中删除最后一位数字,因此我们确信 while 循环将终止。

rev = rev * 10 + num % 10

Here rev*10 will shift the value by left and then add the last digit from the original.
If the original number was 1258, and in the middle of the run time we have rev = 85, num = 12 so:
num%10 = 2
rev*10 = 850
rev*10 + num%10 = 852

这里 rev*10 会将值左移,然后添加原始数字的最后一位。
如果原始数字是 1258,并且在运行时间中间我们有 rev = 85,num = 12 所以:
num%10 = 2
rev*10 = 850
rev*10 + num%10 = 852

回答by Harsh Kevadia

import java.util.Scanner;

public class Reverse_order_integer {
    private static Scanner scan;

    public static void main(String[] args) {
        System.out.println("\t\t\tEnter Number which you want to reverse.\n");
        scan = new Scanner(System.in);
        int number = scan.nextInt();
        int rev_number = reverse(number);
        System.out.println("\t\t\tYour reverse Number is = \"" + rev_number
                           + "\".\n");
    }

    private static int reverse(int number) {
        int backup = number;
        int count = 0;
        while (number != 0) {
            number = number / 10;
            count++;
        }
        number = backup;
        int sum = 0;
        for (int i = count; i > 0; i--) {
            int sum10 = 1;
            int last = number % 10;
            for (int j = 1; j < i; j++) {
                sum10 = sum10 * 10;
            }
            sum = sum + (last * sum10);
            number = number / 10;
        }
        return sum;
    }
}

回答by pankaj

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

这将返回整数的反转

回答by Ganesa Vijayakumar

Simply you can use this

只需你可以使用这个

    public int getReverseInt(int value) {
        int resultNumber = 0;
        for (int i = value; i !=0; i /= 10) {
            resultNumber = resultNumber * 10 + i % 10;
        }
        return resultNumber;        
    }

You can use this method with the given value which you want revers.

您可以将此方法与您想要反转的给定值一起使用。

回答by user3623719

public static int reverse(int x) {
    boolean negetive = false;
    if (x < 0) {
        x = Math.abs(x);
        negative = true;
    }

    int y = 0, i = 0;
    while (x > 0) {
        if (i > 0) {
            y *= 10;
        }

        y += x % 10;
        x = x / 10;
        i++;
    }
    return negative ? -y : y;
}

回答by H2OPolo

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.

你写出你的原始代码很好。我有另一种方法来编码这个反转整数的概念。我只允许最多 10 位数字。但是,我将假设用户不会输入零。

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");

回答by C.A

I used Stringand I converted initially the intto String.Then I used the reverse method. I found the reverse of the number in Stringand then I converted the string back to int. Here is the program.

我使用String并最初将 转换intString。然后我使用了相反的方法。我找到了数字的反向,String然后我将字符串转换回int. 这是程序。

import java.util.*;

public class Panathinaikos {
    public static void my_try()
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the number you want to be reversed");
        int number = input.nextInt();
        String sReverse = Integer.toString(number);
        String reverse = new StringBuffer(sReverse).reverse().toString();
        int Reversed = Integer.parseInt(reverse);
        System.out.print("The number " + number+ " reversed is " + Reversed);
    }
}