Java 在不使用数组的情况下反转 int 值 [英] Java reverse an int value without using array

查看:36
本文介绍了Java 在不使用数组的情况下反转 int 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

推荐答案

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

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

所以相反的数字是 5432.如果你只想要反转数字中的奇数,那么.代码是:

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

这篇关于Java 在不使用数组的情况下反转 int 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆