您的位置:首页 > 其它

Reverse Integer

2016-02-25 12:53 211 查看
又是一个简单的但是都没一次通过的题目, 第一遍刷题就这么差么

自己丑陋的代码 so ugly

class Solution {
public:
int reverse(int x) {
if ((x >= 2147483647) || (x <= -2147483648) || x == 0)
{
return 0;
}
int result = 0;
bool flag = false;
if (x < 0)
{
x = -x;
flag = true;
}

while ((x / 10) != 0)
{
int mod = x % 10;
x = x / 10;
if ((result + mod) > 214748364.7)
{
return 0;
}
result = (result + mod) * 10;
}
result += (x % 10);

if (flag == true)
{
result = result * -1;
}
return result;
}
};
有几个地方很丑 

1. 不需要要那么多的中间变量啊 什么mod之类的 不过买

2. 

if ((result + mod) > 214748364.7)
这个很拙劣啊 虽然还是看test case 错误想出来的。。。
大家都是 result = result * 10 + x %10; 而我是奇葩的 result = (result + x %10)*10 

关键其实是可以改变result的type 这样就避免了在运算过程中的overflow从而只要最后check就好 改成long long

但是如果是64 bit的机器呢,long long也不管用了 所以提前判断也不是一个差的选择

class Solution {
public:
int reverse(int x) {

long long result = 0;
bool flag = false;
if (x < 0)
{
x = -x;
flag = true;
}

while (x != 0)
{
result = result * 10 + x % 10;
x = x / 10;
}
//result += (x % 10);

if (flag == true)
{
result = result * -1;
}
if ((result >= 2147483647) || (result <= -2147483648) )
{
return 0;
}
return result;
}
};

或者是方法二如果overflow 比较就会不同 但是check for

public int reverse(int x)
{
int result = 0;

while (x != 0)
{
int tail = x % 10;
int newResult = result * 10 + tail;
if ((newResult - tail) / 10 != result)
{ return 0; }
result = newResult;
x = x / 10;
}

return result;
}


3. 写数字显得很不专业啊 要用0xf7777777 INT_MIN

4.为什么我要特别handle 负数的情况

其实根本不需要啊!!!

Rethink
for a while. And actually, we don't need to use special logic to handle '+' and '-', because the sign can be kept during calculating. 

good link : https://leetcode.com/discuss/18785/my-accepted-15-lines-of-code-for-java https://leetcode.com/discuss/18523/shortest-code-possible-in-c
class Solution {
public:
int reverse(int x) {
long long res = 0;
while(x) {
res = res*10 + x%10;
x /= 10;
}
return (res<INT_MIN || res>INT_MAX) ? 0 : res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: