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

查看:99
本文介绍了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循环
rev = 5输入= 234
第二次
rev = 5 * 10 + 4 = 54输入= 23
第三次
rev = 54 * 10 + 3输入= 2
第四次
rev = 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天全站免登陆