LeetCode 0007

xiaoxiao2021-02-28  8

原题链接

我的解法:

直接转置即可

class Solution { public: int reverse(int x) { const int max = 0x7fffffff; const int min = 0x80000000; long long res = 0; while(x) { res *= 10; res += (x % 10); if(res > max || res < min) { return 0; } x /= 10; } return res; } };

最快答案的解法:

大概思路是一致的,不过多了一些预处理

class Solution { public: int reverse(int x) { bool isNegative = false; int revX = 0, temp = x, count=1; int limitX = 0x7fffffff/10, limitY=0x7fffffff%10; if (x < 0) {isNegative = true; temp = x * -1;} while(temp > 0) { if ((count == 10) && ((revX > limitX) || ((revX == limitX) && (temp > limitY)))) return 0; revX = (revX * 10) + temp % 10; temp = temp/10; count++; } if (isNegative) revX = revX * -1; return revX; } };
转载请注明原文地址: https://www.6miu.com/read-1100042.html

最新回复(0)