You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
7. Reverse Integer
Total Accepted: 180058
Total Submissions: 759486
Difficulty: Easy
Contributors: Admin
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
这一题乍一看十分简单,噌噌噌写好,心想一天一道算法今天这么快就收工了:
input : x
int reverse=0;
for(int num;x;x/=10)
{
num=x%10;
reverse=reverse*10+num;
}
return reverse;
提交不通过,发现没有考虑负数
考虑负数后再次提交仍然不通过,发现没有考虑溢出
考虑溢出后增加了许多判断条件,代码变得臃肿:
class Solution
{
public:
int reverse(int x)
{
int max=2147483647;//有符号int最大值
int min=-2147483648;//有符号int最小值
//转换为正数
if(x==min)return 0;//x=mix不方便去符号,手动判断排除
bool sign=x>0?true:false;
if(sign==false)x=-x;
int reverse=0;
for(int num,tmp;x;x/=10)
{
num=x%10;
tmp=reverse*10+num;
if(reverse<=(max-num)/10) //a*b+c>max=>a>(max-c)/b
{
reverse=tmp;
}
else
{
return 0;
}
}
return sign?reverse:-reverse;
}
};
The text was updated successfully, but these errors were encountered: