Algorithm
OJ address
Leetcode website : 7. Reverse Integer
Description
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2的31次方, 2的31次方 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution in C (one)
int reverse(int x) {
int t = 0;
if (x == 0) return 0;
while (!x%10) {
x/=10;
}
int sum = 0;
long long reallysum = 0;
while (x) {
reallysum *=10;
sum *= 10;
t = x%10;
reallysum+=t;
sum+=t;
x/=10;
}
if (reallysum != sum) return 0;
return sum;
}
Solution in C (Two)
int reverse(int x) {
int t = 0;
if (x == 0) return 0;
while (!x%10) {
x/=10;
}
int sum = 0;
int tmp = 0;
while (x) {
sum *= 10;
if (sum/10 != tmp) return 0;
t = x%10;
sum+=t;
x/=10;
tmp = sum;
}
return sum;
}
My Idea
题目含义是,给定一个int类型的整数,然后进行数字反转,输出。
- 反转后,将前导0去掉,例如2300 -> 0023 ->23
- 如果超过 INT_MAX , 或者小鱼 INT_MIN,则输出0,关于这个如何判断,有两种简单的方法,第一种方法是用long long来存取变量,如果大于INT_MAX或者小于INT_MIN,则输出0.第二种方法就是如果超出最大值,或小于最小值,则你最高位后面的尾数是会因为超出最大值而跟着改变的,所以你只要检测尾数如果变化,就输出0即可,这就是我代码里的第二种方法。