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類型的整數(shù),然后進行數(shù)字反轉(zhuǎn)首繁,輸出作郭。
- 反轉(zhuǎn)后,將前導0去掉弦疮,例如2300 -> 0023 ->23
- 如果超過 INT_MAX , 或者小魚 INT_MIN夹攒,則輸出0,關(guān)于這個如何判斷胁塞,有兩種簡單的方法咏尝,第一種方法是用long long來存取變量,如果大于INT_MAX或者小于INT_MIN啸罢,則輸出0.第二種方法就是如果超出最大值编检,或小于最小值,則你最高位后面的尾數(shù)是會因為超出最大值而跟著改變的伺糠,所以你只要檢測尾數(shù)如果變化蒙谓,就輸出0即可,這就是我代碼里的第二種方法训桶。