整数反转(7)
7. 整数反转 - 力扣(LeetCode)
解法:
class Solution {
public:int reverse(int x){int res = 0;int remainder = 0;bool negative = false;if (x < 0) {negative = true;}do {remainder = x % 10;x = x / 10;//由于只能使用int取值范围的数字,所以需要提前确认是否超出int取值的范围if ((!negative && res > (numeric_limits<int>::max() - remainder) / 10) ||(negative && res < (numeric_limits<int>::min() + abs(remainder)) / 10)){return 0;}res = res * 10 + remainder;}while (x != 0);return res;}
};
总结:
计算时间复杂度O(log x),即x的位数;空间复杂度O(1).