Java 不使用数组反转 int 值

发布于 2024-09-25 14:01:43 字数 246 浏览 8 评论 0原文

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

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

2024-10-02 14:01:44
public int getReverseNumber(int number)
{
    int reminder = 0, result = 0;
    while (number !=0)
    {
        if (number >= 10 || number <= -10)
        {
            reminder = number % 10;
            result = result + reminder;
            result = result * 10;
            number = number / 10;
        }
        else
        {
            result = result + number;
            number /= 10;
        }
    }
    return result;

}

// 上面的代码也适用于负数

public int getReverseNumber(int number)
{
    int reminder = 0, result = 0;
    while (number !=0)
    {
        if (number >= 10 || number <= -10)
        {
            reminder = number % 10;
            result = result + reminder;
            result = result * 10;
            number = number / 10;
        }
        else
        {
            result = result + number;
            number /= 10;
        }
    }
    return result;

}

// The above code will work for negative numbers also

人生戏 2024-10-02 14:01:44

反转整数

  int n, reverse = 0;
  Scanner in = new Scanner(System.in);
  n = in.nextInt();

  while(n != 0)
  {
      reverse = reverse * 10;
      reverse = reverse + n%10;
      n = n/10;
  }

  System.out.println("Reverse of the number is " + reverse);

Reversing integer

  int n, reverse = 0;
  Scanner in = new Scanner(System.in);
  n = in.nextInt();

  while(n != 0)
  {
      reverse = reverse * 10;
      reverse = reverse + n%10;
      n = n/10;
  }

  System.out.println("Reverse of the number is " + reverse);
一袭水袖舞倾城 2024-10-02 14:01:44
 public static int reverseInt(int i) {
    int reservedInt = 0;

    try{
        String s = String.valueOf(i);
        String reversed = reverseWithStringBuilder(s);
        reservedInt = Integer.parseInt(reversed);

    }catch (NumberFormatException e){
        System.out.println("exception caught was " + e.getMessage());
    }
    return reservedInt;
}

public static String reverseWithStringBuilder(String str) {
    System.out.println(str);
    StringBuilder sb = new StringBuilder(str);
    StringBuilder reversed = sb.reverse();
    return reversed.toString();
}
 public static int reverseInt(int i) {
    int reservedInt = 0;

    try{
        String s = String.valueOf(i);
        String reversed = reverseWithStringBuilder(s);
        reservedInt = Integer.parseInt(reversed);

    }catch (NumberFormatException e){
        System.out.println("exception caught was " + e.getMessage());
    }
    return reservedInt;
}

public static String reverseWithStringBuilder(String str) {
    System.out.println(str);
    StringBuilder sb = new StringBuilder(str);
    StringBuilder reversed = sb.reverse();
    return reversed.toString();
}
我不会写诗 2024-10-02 14:01:44
public static int reverse(int x) {
    int tmp = x;
    int oct = 0;
    int res = 0;
    while (true) {
        oct = tmp % 10;
        tmp = tmp / 10;
        res = (res+oct)*10;
        if ((tmp/10) == 0) {
            res = res+tmp;
            return res;
        }
    }
}
public static int reverse(int x) {
    int tmp = x;
    int oct = 0;
    int res = 0;
    while (true) {
        oct = tmp % 10;
        tmp = tmp / 10;
        res = (res+oct)*10;
        if ((tmp/10) == 0) {
            res = res+tmp;
            return res;
        }
    }
}
花海 2024-10-02 14:01:44
public class JavaReverseNumbers {
public static void main(String args[]) {

    Scanner keyboard = new Scanner(System.in);

    String input;

    long remainder,inputlength,counter = 1;
    System.out.println("Enter a number: ");
    input = keyboard.next();
    long i = Integer.parseInt(input); 
    inputlength = input.length();
    
    while (counter <= inputlength){
        remainder = i % 10;
        i  = i / 10;
        System.out.print(remainder);
        counter++;
    }
}}
    

我是这个程序的新手,对我的错误感到抱歉。
这里我使用了String类型到int类型的转换

public class JavaReverseNumbers {
public static void main(String args[]) {

    Scanner keyboard = new Scanner(System.in);

    String input;

    long remainder,inputlength,counter = 1;
    System.out.println("Enter a number: ");
    input = keyboard.next();
    long i = Integer.parseInt(input); 
    inputlength = input.length();
    
    while (counter <= inputlength){
        remainder = i % 10;
        i  = i / 10;
        System.out.print(remainder);
        counter++;
    }
}}
    

I'm new to this program, sorry for my mistakes.
Here I used a conversion from String type to int type

没︽人懂的悲伤 2024-10-02 14:01:43

Java 反转 int 值 - 原理

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

  2. 将整数乘以 10 会将其“向左推”,在该数字的右侧显示零,示例:(5 * 10) = 50

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

Java 反转 int 值 - 伪代码:

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

b.取出该数字 (4) 并将其添加到新的 returnedNum 中。

c.将 reveredNum 乘以 10 (4 * 10) = 40,这会在 (4) 的右侧显示一个零。

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

e。使用 123 重复步骤 a

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;
}

在真实的工作世界中,您永远不会做这样的事情。然而,在没有帮助的情况下解决问题的过程是将能够解决问题的人和那些想要解决问题但不能解决问题的人区分开来的,除非他们是由博客上的好人填鸭式的。

Java reverse an int value - Principles

  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

Java reverse an int value - Pseudocode:

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

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

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

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

e. Repeat at step a with 123

Java reverse an int value - Working code

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.

夜空下最亮的亮点 2024-10-02 14:01:43

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

所以反转后的数是5432。
如果你只想要反转数中的奇数。
代码是:

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

    }
    input = input / 10; 
}

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

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

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

    }
    input = input / 10; 
}
拥醉 2024-10-02 14:01:43

只需使用此方法

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

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

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.

哆啦不做梦 2024-10-02 14:01:43
while (num != 0) {
    rev = rev * 10 + num % 10;
    num /= 10;
}

这就是我用来解决这个问题的解决方案,并且效果很好。
更多详细信息:

num % 10

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

num /= 10

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

rev = rev * 10 + num % 10

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

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.

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

落在眉间の轻吻 2024-10-02 14:01:43

没有循环的Java解决方案。响应速度更快。

int numberToReverse;//your number 
StringBuilder sb=new StringBuilder();
sb.append(numberToReverse);
sb=sb.reverse();
String intermediateString=sb.toString();
int reversedNumber=Integer.parseInt(intermediateString);

Java solution without the loop. Faster response.

int numberToReverse;//your number 
StringBuilder sb=new StringBuilder();
sb.append(numberToReverse);
sb=sb.reverse();
String intermediateString=sb.toString();
int reversedNumber=Integer.parseInt(intermediateString);
最美的太阳 2024-10-02 14:01:43
int aa=456;
int rev=Integer.parseInt(new StringBuilder(aa+"").reverse());
int aa=456;
int rev=Integer.parseInt(new StringBuilder(aa+"").reverse());
雨的味道风的声音 2024-10-02 14:01:43
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;
    }
}
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;
    }
}
温柔嚣张 2024-10-02 14:01:43

为了得到任何数字的最后一位数字,我们将它除以 10,这样我们要么得到零,要么得到一个放在最后的数字,当我们连续这样做时,我们得到作为整数反转的整个数字。

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

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);
初懵 2024-10-02 14:01:43
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));
}

这将返回整数的反转

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

蛮可爱 2024-10-02 14:01:43

只是补充一下,希望使解决方案更加完整。

@sheki 的逻辑已经给出了在 Java 中反转整数的正确方法。如果您假设您使用的输入和获得的结果始终落在 [-2147483648, 2147483647] 范围内,那么您应该可以安全地使用 @sheki 的代码。否则,捕获异常将是一个很好的做法。

Java 8 引入了方法 addExactsubtractExactmultiplyExact< /em>toIntExact 。这些方法将在溢出时抛出ArithmeticException。因此,您可以使用下面的实现来实现一种干净且更安全的方法来反转整数。一般来说,我们可以使用上述方法进行数学计算并显式处理溢出问题,如果实际使用中存在溢出的可能性,则始终建议这样做。

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;
}

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;
}
甜点 2024-10-02 14:01:43
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class intreverse
{
public static void main(String...a)throws Exception
{
    int no;
    int rev = 0;
    System.out.println("Enter The no to be reversed");
    InputStreamReader str=new InputStreamReader(System.in);
    BufferedReader br =new BufferedReader(str);
    no=Integer.parseInt(br.readLine().toString());
    while(no!=0)
    {
        rev=rev*10+no%10;
        no=no/10;

    }
    System.out.println(rev);
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class intreverse
{
public static void main(String...a)throws Exception
{
    int no;
    int rev = 0;
    System.out.println("Enter The no to be reversed");
    InputStreamReader str=new InputStreamReader(System.in);
    BufferedReader br =new BufferedReader(str);
    no=Integer.parseInt(br.readLine().toString());
    while(no!=0)
    {
        rev=rev*10+no%10;
        no=no/10;

    }
    System.out.println(rev);
}
}
秋叶绚丽 2024-10-02 14:01:43
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;
}
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;
}
山人契 2024-10-02 14:01:43

这是一个完整的解决方案(如果数字溢出则返回0):

public int reverse(int x) {
    boolean flag = false;

    // Helpful to check if int is within range of "int"
    long num = x;

    // if the number is negative then turn the flag on.
    if(x < 0) {
        flag = true;
        num = 0 - num;
    }

    // used for the result.
    long result = 0;

    // continue dividing till number is greater than 0
    while(num > 0) {
        result = result*10 + num%10;
        num= num/10;
    }

    if(flag) {
        result = 0 - result;
    }

    if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
        return 0;
    }
    return (int) result;
}

Here is a complete solution(returns 0 if number is overflown):

public int reverse(int x) {
    boolean flag = false;

    // Helpful to check if int is within range of "int"
    long num = x;

    // if the number is negative then turn the flag on.
    if(x < 0) {
        flag = true;
        num = 0 - num;
    }

    // used for the result.
    long result = 0;

    // continue dividing till number is greater than 0
    while(num > 0) {
        result = result*10 + num%10;
        num= num/10;
    }

    if(flag) {
        result = 0 - result;
    }

    if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
        return 0;
    }
    return (int) result;
}
浅沫记忆 2024-10-02 14:01:43
    Scanner input = new Scanner(System.in);
        System.out.print("Enter number  :");
        int num = input.nextInt(); 
        System.out.print("Reverse number   :");
        int value;
        while( num > 0){
            value = num % 10;
            num  /=  10;
            System.out.print(value);  //value = Reverse
            
             }
    Scanner input = new Scanner(System.in);
        System.out.print("Enter number  :");
        int num = input.nextInt(); 
        System.out.print("Reverse number   :");
        int value;
        while( num > 0){
            value = num % 10;
            num  /=  10;
            System.out.print(value);  //value = Reverse
            
             }
青柠芒果 2024-10-02 14:01:43
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));

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

    }
不顾 2024-10-02 14:01:43

很高兴您写出了原始代码。我有另一种方法来编码反转整数的概念。我最多只允许 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");

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");
许你一世情深 2024-10-02 14:01:43

即使传递负整数,它也会给出负整数
试试这个...

public int reverse(int result) {

    long newNum=0,old=result;
    result=(result>0) ? result:(0-result);

    while(result!=0){
        newNum*=10;
        newNum+=result%10;
        result/=10;
        if(newNum>Integer.MAX_VALUE||newNum<Integer.MIN_VALUE)
            return 0;
    }
    if(old > 0)
        return (int)newNum;
    else if(old < 0)
        return (int)(newNum*-1);
    else 
        return 0;
}

Even if negative integer is passed then it will give the negative integer
Try This...

public int reverse(int result) {

    long newNum=0,old=result;
    result=(result>0) ? result:(0-result);

    while(result!=0){
        newNum*=10;
        newNum+=result%10;
        result/=10;
        if(newNum>Integer.MAX_VALUE||newNum<Integer.MIN_VALUE)
            return 0;
    }
    if(old > 0)
        return (int)newNum;
    else if(old < 0)
        return (int)(newNum*-1);
    else 
        return 0;
}
一杯敬自由 2024-10-02 14:01:43

这是反转整数的最短代码

int i=5263; 
System.out.println(Integer.parseInt(new StringBuffer(String.valueOf(i) ).reverse().toString()));

This is the shortest code to reverse an integer

int i=5263; 
System.out.println(Integer.parseInt(new StringBuffer(String.valueOf(i) ).reverse().toString()));
平生欢 2024-10-02 14:01:43

123 映射到 321,可以计算为 3*(10^2)+2*(10^1)+1
使用两个函数来计算(10^N)。第一个函数计算 N 的值。第二个函数计算 10 的 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);
    }
}

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);
    }
}
最偏执的依靠 2024-10-02 14:01:43

如果想法不是使用数组或字符串,则必须通过一次从末尾读取数字来完成整数的反转。下面详细解释一下,以帮助新手。

伪代码:

  1. 让我们从reversed_number = 0 和需要反转的original_number 的某个值开始。
  2. the_last_digit=original_number % 10(即除以10后的提醒)
  3. original_number=original_number/10(因为我们已经有了最后一位数字,所以从original_number中删除最后一位数字)
  4. reversed_number=reversed_number * 10+last_digit(reversed_number乘以10) ,以便将最后一个数字添加到其中)
  5. 重复步骤2到4,直到original_number变为0。当original_number = 0时,reversed_number将与original_number相反。

有关步骤 4 的更多信息:如果每次向您提供一个数字,并要求您将其附加在数字末尾,您会怎么做 - 将原始数字向左移动一位以适应数字新数字。如果数字 23 必须变成 234,则将 23 乘以 10,然后加上 4。234

= 23x10 + 4;

代码:

public static int reverseInt(int original_number) {
        int reversed_number = 0;
        while (original_number > 0) {
            int last_digit = original_number % 10;
            original_number = original_number / 10;
            reversed_number = reversed_number * 10 + last_digit;    
        }
        return reversed_number;
    }

If the idea is not to use arrays or string, reversing an integer has to be done by reading the digits of a number from the end one at a time. Below explanation is provided in detail to help the novice.

pseudocode :

  1. lets start with reversed_number = 0 and some value for original_number which needs to be reversed.
  2. the_last_digit = original_number % 10 (i.e, the reminder after dividing by 10)
  3. original_number = original_number/10 (since we already have the last digit, remove the last digit from the original_number)
  4. reversed_number = reversed_number * 10 + last_digit (multiply the reversed_number with 10, so as to add the last_digit to it)
  5. repeat steps 2 to 4, till the original_number becomes 0. When original_number = 0, reversed_number would have the reverse of the original_number.

More info on step 4: If you are provided with a digit at a time, and asked to append it at the end of a number, how would you do it - by moving the original number one place to the left so as to accommodate the new digit. If number 23 has to become 234, you multiply 23 with 10 and then add 4.

234 = 23x10 + 4;

Code:

public static int reverseInt(int original_number) {
        int reversed_number = 0;
        while (original_number > 0) {
            int last_digit = original_number % 10;
            original_number = original_number / 10;
            reversed_number = reversed_number * 10 + last_digit;    
        }
        return reversed_number;
    }
好倦 2024-10-02 14:01:43

这是一个过时的问题,但作为其他人的参考
首先reverseNum必须初始化为0;

input%10 用于获取输入中的最后一位数字

input/10 用于删除输入中的最后一位数字,您已将其添加到reverseNum

假设输入是 135

135 % 10 是 5
由于反转数被初始化为0
现在reverseNum将为5

然后我们通过将135除以10来去掉5

现在输入将只是13

您的代码循环执行这些步骤,直到所有数字都添加到反转的数字中,或者换句话说,直到输入变为0。

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.

路弥 2024-10-02 14:01:43
while (input != 0) {
  reversedNum = reversedNum * 10 + input % 10;
  input = input / 10;
}

设一个数为 168,
+ 输入 % 10 返回最后一位数字作为提醒,即 8,但下次它应该返回 6,因此数字必须从 168 减少到 16,因为将 168 除以 10 会得到 16 而不是 16.8,因为变量输入应该是整数类型在上面的程序中。

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

let a number be 168,
+ input % 10 returns last digit as reminder i.e. 8 but next time it should return 6,hence number must be reduced to 16 from 168, as divide 168 by 10 that results to 16 instead of 16.8 as variable input is supposed to be integer type in the above program.

硪扪都還晓 2024-10-02 14:01:43

如果你想反转任何数字,比如 1234,并且你想反转这个数字,让它看起来像 4321。首先,初始化 3 个变量 int org ; int 反向 = 0;和int提醒;
然后把你的逻辑写成

    Scanner input = new Scanner (System.in);
    System.out.println("Enter number to reverse ");
    int org = input.nextInt();
    int getReminder;
    int r = 0;
    int count = 0;

    while (org !=0){
        getReminder = org%10;
         r = 10 * r + getReminder;
         org = org/10;



    }
        System.out.println(r);

    }

If you wanna reverse any number like 1234 and you want to revers this number to let it looks like 4321. First of all, initialize 3 variables int org ; int reverse = 0; and int reminder ;
then put your logic like

    Scanner input = new Scanner (System.in);
    System.out.println("Enter number to reverse ");
    int org = input.nextInt();
    int getReminder;
    int r = 0;
    int count = 0;

    while (org !=0){
        getReminder = org%10;
         r = 10 * r + getReminder;
         org = org/10;



    }
        System.out.println(r);

    }
梦在深巷 2024-10-02 14:01:43

求小于或等于整数的10的最大幂的方法:(递归)

public static int powerOfTen(int n) {
    if ( n < 10)
        return 1;
    else
        return 10 * powerOfTen(n/10); 
}

反转实际整数的方法:(递归)

public static int reverseInteger(int i) {
    if (i / 10 < 1)
        return i ;
    else
        return i%10*powerOfTen(i) + reverseInteger(i/10);
}

A method to get the greatest power of ten smaller or equal to an integer: (in recursion)

public static int powerOfTen(int n) {
    if ( n < 10)
        return 1;
    else
        return 10 * powerOfTen(n/10); 
}

The method to reverse the actual integer:(in recursion)

public static int reverseInteger(int i) {
    if (i / 10 < 1)
        return i ;
    else
        return i%10*powerOfTen(i) + reverseInteger(i/10);
}
决绝 2024-10-02 14:01:43

您可以使用递归来解决这个问题。

首先使用以下递归函数获取整数的长度。

int Length(int num,int count){
    if(num==0){
        return count;
    }
    else{
        count++;
        return Lenght(num/10,count);
    }
}

然后你可以简单地将数字的余数乘以 10^(整数的长度 - 1)。

int ReturnReverse(int num,int Length,int reverse){
    if(Length!=0){
        reverse = reverse + ((num%10) * (int)(Math.pow(10,Length-1)));
        return ReturnReverse(num/10,Length-1,reverse);
    }
    return reverse;
}

整个源代码:

import java.util.Scanner;

public class ReverseNumbers {

    int Length(int num, int count) {
        if (num == 0) {
            return count;
        } else {
            return Length(num / 10, count + 1);
        }
    }

    int ReturnReverse(int num, int Length, int reverse) {
        if (Length != 0) {
            reverse = reverse + ((num % 10) * (int) (Math.pow(10, Length - 1)));
            return ReturnReverse(num / 10, Length - 1, reverse);
        }
        return reverse;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int N = scanner.nextInt();

        ReverseNumbers reverseNumbers = new ReverseNumbers();
        reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), 0));

        scanner.close();
    }
}

You can use recursion to solve this.

first get the length of an integer number by using following recursive function.

int Length(int num,int count){
    if(num==0){
        return count;
    }
    else{
        count++;
        return Lenght(num/10,count);
    }
}

and then you can simply multiply remainder of a number by 10^(Length of integer - 1).

int ReturnReverse(int num,int Length,int reverse){
    if(Length!=0){
        reverse = reverse + ((num%10) * (int)(Math.pow(10,Length-1)));
        return ReturnReverse(num/10,Length-1,reverse);
    }
    return reverse;
}

The whole Source Code :

import java.util.Scanner;

public class ReverseNumbers {

    int Length(int num, int count) {
        if (num == 0) {
            return count;
        } else {
            return Length(num / 10, count + 1);
        }
    }

    int ReturnReverse(int num, int Length, int reverse) {
        if (Length != 0) {
            reverse = reverse + ((num % 10) * (int) (Math.pow(10, Length - 1)));
            return ReturnReverse(num / 10, Length - 1, reverse);
        }
        return reverse;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int N = scanner.nextInt();

        ReverseNumbers reverseNumbers = new ReverseNumbers();
        reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), 0));

        scanner.close();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文