题目
英文原文
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
我的翻译
给定一个32位带符号(signed,即确定正负号)整数,返回翻转后的值。
注解:
假定我们只能处理32位带符号整数。你的函数需要在溢出时返回0。
样例
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
我的解法
思路分析
翻转整数部分没什么可说的,只需要根据两个数学知识: num%10 得到 num的个位数 , num / 10得到的是num去除个位以后的数字,即可。
重点在于溢出判断,我的做法是判断 (num*10)/10 == num , 如果不等于,则说明 num * 10 已经溢出,此时返回0即可。
AC代码
class Solution {
public:
int reverse(int x) {
int Ispos = 1;//ispostive是否正数,负数化为正数处理
if ( x < 0){
Ispos = 0;
x = -x;
}
int ans = 0;
while(x){
ans += x % 10;
x = x / 10;
if (x) {
int ans1 = ans;
ans *= 10;
if ( ans1 != ans / 10){
return 0;
}
}
}
if( Ispos){
return ans;
}else{
return -ans;
}
}
};
时间:22ms
他人代码赏析
他的代码的优化之处在于溢出判断。并没有采用int声明变量,而是long。然后判断结果和int机内最大最小值比较。具体算法实现思想并没有改进,因此时间并没有优化很多。实际上这个问题O(n)已经是最小时间复杂度了。毕竟翻转整数总要把整个整数扫描一遍吧。
static int x = []() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
int reverse(int x) {
long answer = 0;
while (x != 0) {
answer = answer * 10 + x % 10;
if (answer > INT_MAX || answer < INT_MIN) return 0;
x /= 10;
}
return (int)answer;
}
};
时间:9ms
说明:本文除注明外,全文原创。也在我的个人博客上发布:https://www.watwg.com/