2023每日刷题(十)
Leetcode—7.整数反转
关于为什么要设long变量
参考自这篇博客
long可以表示-2147483648而且只占4个字节,所以能满足题目要求
复杂逻辑版实现代码
int reverse(int x){int arr[32] = {0};long y;int flag = 1;if(x < 0) {flag = -1;y = x;y = -y;} else {y = x;}int ans = 0;if(y == 0) {ans = 0;}int i = 0;while(y) {arr[i++] = y % 10;y /= 10;}int cnt = i;int pos[10] = {2, 1, 4, 7, 4, 8, 3, 6, 4, 7};int flag2 = 0;if(cnt == 10) {int k = 0;int tmp1 = 0;int tmp2 = 0;while(k < 10) {tmp1 *= 10;tmp2 *= 10;if(k == 9) {if(flag == 1 && arr[k] <= pos[k]) {ans = tmp1 + arr[k];break;} else if(flag == -1 && arr[k] <= pos[k] + 1) {if(arr[k] == pos[k] + 1) {ans = tmp1*(-1)-8;} else {ans = tmp1*(-1)-arr[k];}break;} else {ans = 0;break;}}tmp1 += arr[k];tmp2 += pos[k];if(tmp1 < tmp2) {flag2 = 1;break;} else if(tmp1 > tmp2) {ans = 0;break;}k++;}} if(cnt < 10 || flag2 == 1) {int tmp1 = 0;int j = 0;while(j < cnt) {tmp1 *= 10;tmp1 += arr[j++];}ans = tmp1;if(flag == -1) {ans *= -1;}}return ans;
}
运行结果
简洁版实现代码
int reverse(int x){long ans = 0;// long类型:防止反转过程溢出long y = x;int d, flag;flag = (x < 0 ? -1 : 1);if(x < 0) {y = -y;}while(y != 0) {d = y % 10;y /= 10;ans = ans * 10 + d;}ans = flag * ans;if(ans < INT_MIN || ans > INT_MAX) {return 0;}return ans;
}
运行结果
更简洁版实现代码
其实也可以不判断符号
int reverse(int x){long ans = 0;// long类型:防止反转过程溢出long y = x;int d;while(y != 0) {d = y % 10;y /= 10;ans = ans * 10 + d;}if(ans < INT_MIN || ans > INT_MAX) {return 0;}return ans;
}
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!