2016年11月29日 星期二

[LeetCode] 9. Palindrome Number

轉自LeetCode

Determine whether an integer is a palindrome. Do this without extra space.


Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

<Solution>

這題是要檢查數字是不是回文 (參考資料)

12321 => true
1233  => false
-12  => false
6    => true

解題概念就是把頭和尾的數字抓出來,然後比較

接著把頭和尾去掉,重複上一步驟

例如 head = 1223 / 1000 = 1,tail = 1223 % 10 = 3

head != tail,return false

code如下

C++

class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) {
return false;
}
else if(x < 10) {
return true;
}
int divNum = 1;
//> calculate the max div number
while(x / divNum >= 10) {
divNum *= 10;
}
int head, tail;
while(x > 0) {
head = x / divNum;
tail = x % 10;
//> check palindrome
if(head != tail) {
return false;
}
//> remove head and tail digits
x = (x % divNum) / 10;
divNum /= 100;
}
return true;
}
};
Java
public class Solution {
public boolean isPalindrome(int x) {
if(x < 0) {
return false;
}
else if(x < 10) {
return true;
}
//> calculate the max div number
int divNum = 10;
while((x/divNum) >= 10) {
divNum *= 10;
}
while(x > 0) {
int head = x / divNum;
int tail = x % 10;
//> check palindrome
if(head != tail) {
return false;
}
//> remove head and tail digits
x = (x % divNum) / 10;
divNum /= 100;
}
return true;
}
}

沒有留言:

張貼留言