1. 程式人生 > >【LeetCode】126.Palindrome Number

【LeetCode】126.Palindrome Number

題目描述(Easy)

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

題目連結

https://leetcode.com/problems/palindrome-number/description/

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.

Follow up:

Coud you solve it without converting the integer to a string?

演算法分析

不斷取當前第一位和最後一位進行比較,往中間收縮,直到找到不一樣的位。

提交程式碼:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        int decades = 1;
        
        while(x / decades >= 10) decades *= 10;
        
        while(x > 0) {
            int beg = x / decades;
            int end = x % 10;
            if (beg != end) return false;
            x = x % decades / 10;
            
            decades /= 100;
        }
        
        return true;
    }
};