整数的倒数 [英] Reverse digits of an integer
本文介绍了整数的倒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何反转数字?
示例1:x = 123,返回321示例2:x = -123,返回-321
Example1: x = 123, return 321 Example2: x = -123, return -321
这是我的答案:
public int reverse(int x) {
int result = 0;
while(x != 0){
result = result * 10 + x % 10;
x = x / 10;
}
return result;
}
但是当我输入1534236469时,它将输出1056389759,这是错误的.您如何看待我的课程?谢谢.
but when I input 1534236469 , it will output 1056389759 , this is wrong. what do you think about my program? thanks.
推荐答案
您还可以输入x> 0(尽管没关系),然后还必须考虑负数,所以我对逻辑进行了如下更改(也请使用长久以避免溢出):
You can write x >0 (doesn't matter though )also after that you have to consider negative numbers , I made that change to your logic as follows (Also use long long to avoid overflow):
long long reverse(long long x)
{
int sign = 1;
long long ans=0;
if(x < 0)
sign = -1;
x = abs(x);
while(x > 0)
{
ans *= 10;
ans += x%10;
x /=10;
}
return ans*sign;
}
这篇关于整数的倒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文