您的位置:首页 > 其它

LeetCode: Reverse Integer,Palindrome Number

2017-12-17 06:24 267 查看
Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

"""1. 26 ms
时间复杂度是O(log10(n))
"""
class Solution {
public:
int reverse(int x) {
int result = 0;
int new_result = 0;
while(x){
new_result = result * 10 + x % 10;
x /= 10;
//一定是将x完全颠倒过来那一步才可能发生越界,所以可以这样判断
if (new_result/10 != result){
return 0;
}
result = new_result;
}
return result;
}
};


"""2, 更短的写法
"""
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;
}
};


Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

"""1, reverse一半的数字, 152 ms, beats 66.69%
注意负数和数字位数不能被2整除的情形
"""
public:
bool isPalindrome(int x) {
4000
if (x < 0)
return false;

int len = 0;
int x_front = x;
while(x){
x /= 10;
len += 1;
}
int reversed_len = len/2;

int x_back = 0;
for (int i=0; i<reversed_len; i++){
x_back = x_back * 10 + x_front % 10;
x_front /= 10;
}

//10,20,80等都不是,所以加了一个&& len % 2 != 0
if (x_front == x_back || (x_front/10 == x_back && len % 2 != 0))
return true;
else
return false;
}
};


"""2, 更简洁一些的写法,172 ms
先多检查特殊的情况,后面就简洁一些了。
"""
class Solution {
public:
bool isPalindrome(int x) {
if(x<0 || (x!=0 && x%10 == 0)) return false;
int sum=0;
while(x>sum)
{
sum = sum*10 + x%10;
x = x/10;
}
return (x==sum) || (x==sum/10);
}
};


一个有趣的讨论:

Impossible to solve without extra space. Always need space for constants, variables or whatever. Recursion calls will take space for call stack.

If you are talking about constant space, then even declaring a string / stack will take constant space. (In fact at most (log(10, INT_MAX) * sizeof char), which is no worse than declaring an integer or more). Actually, even recursion will take constant space.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: