使用按位移位反转数字
我正在尝试找到一种方法来反转数字而不
- 将其转换为字符串以查找长度
- 反转字符串并将其解析回来
- 运行一个单独的循环来计算长度
我目前正在这样做
public static int getReverse(int num){
int revnum =0;
for( int i = Integer.toString(num).length() - 1 ; num>0 ; i-- ){
revnum += num % 10 * Math.pow( 10 , i );
num /= 10;
}
return revnum;
}
但我想实现上述3个条件。
我正在寻找一种方法,可能使用按位移位运算符或某种其他类型的按位运算。
是否可以 ?如果是这样怎么办?
PS:如果给出 1234 作为输入,它应该返回 4321。我只会反转整数和长整型
I am trying to find a way to reverse a number without
- Converting it to a string to find the length
- Reversing the string and parsing it back
- Running a separate loop to compute the Length
i am currently doing it this way
public static int getReverse(int num){
int revnum =0;
for( int i = Integer.toString(num).length() - 1 ; num>0 ; i-- ){
revnum += num % 10 * Math.pow( 10 , i );
num /= 10;
}
return revnum;
}
But I would Like to implement the above 3 conditions.
I am looking for a way , possibly using the bit wise shift operators or some other kind of bitwise operation.
Is it possible ? If so how ?
PS : If 1234 is given as input it should return 4321. I will only be reversing Integers and Longs
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
怎么样:
代码需要一个非负输入。
这对您来说可能很重要,也可能不重要,但值得注意的是,
getReverse(getReverse(x))
不一定等于x
,因为它不会保留尾随零。How about:
The code expects a non-negative input.
This may or may not matter to you, but it's worth noting that
getReverse(getReverse(x))
does not necessarily equalx
as it won't preserve trailing zeroes.这个怎么样?它也处理负数。
How about this? It handles negative numbers as well.
任何解决方案中都根本不考虑
Integer.MAX_VALUE
或Integer.MIN_VALUE
。例如:如果输入为
-2147483647
或2147483647
,则 o/p 将分别为1126087180
和-1126087180
。请尝试以下处理两个条件的解决方案,因此如果在任何时间点数字超出边界条件,即 INPUT_VALUE > Integer.MAX_VALUE 或
INPUT_VALUE < Integer.MIN_VALUE
它将返回0
Integer.MAX_VALUE
orInteger.MIN_VALUE
is not at all considered in any of the solutions.For eg: if the input is
-2147483647
or2147483647
the o/p will be1126087180
and-1126087180
respectively.Please try the below solutions where both the conditions are handled, so if at any point of time the number is going beyond the boundary conditions i.e.,
INPUT_VALUE > Integer.MAX_VALUE
orINPUT_VALUE < Integer.MIN_VALUE
it would return0