記錄LeetCode第二天(Reverse Integer & Palindrome Number.)
1.Reverse Integer題目
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
2. 例子
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
3. 代碼
class Solution {
public:
int reverse(int x) {
long v=0; //反轉後的值定義為長整形
while(x)
{
v=v*10+x%10;
x=x/10;
}
return (v<INT_MIN || v>INT_MAX) ? 0 : v;//判斷是否越界
}
};
4. 超級簡單但是依然強制有的4。
- 一開始沒有注意到最後傳回值的判斷,還有反轉後v的值會有可能越界,要設定成長整形。最然判斷過是否越界,但是總感覺傳回值是int類型但是其實裡面是long有點可怕。。。
-
和INT_MAX
原來也沒有怎麼用到過。INT_MIN
- 每次一用
就感覺很厲害哈哈哈。? :
5. 題目 Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
6. 例子
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
7. 和上面一樣的代碼不想寫注釋
class Solution {
public:
bool isPalindrome(int x) {
int n = x;
long v = 0;
while(n>0)
{
v = v * 10 + n%10;
n = n/10;
}
return (v==x)? true : false;
}
};
還看到一個思路,隻比較一半,數字大的話會快點叭,但是一開始寫有些情況會可能考慮不到,比如10,100 這種,加上條件以後又發現 0其實滿足條件還要再排除。
class Solution {
public:
bool isPalindrome(int x) {
long v = 0;
if(x%10==0 && x!=0 ) return false;
while(x>v && x>0)
{
v = v*10 + x%10;
x = x/10;
}
return (v==x)||(x==v/10);
}
};