C++ 68ms solution


  • 1
    X
    class Solution {
    public:
        //method 1: reverse x and compare it with the original one
        //long long int reverse(int x) {
        //    bool negflag = x < 0 ? true : false;
        //    x = x > 0 ? x : -x;
        //    long long int ans = 0;
        //    while(x){
        //        ans = ans * 10 + (x % 10);
        //        x /= 10;
        //    }
        //    return negflag ? -ans : ans; 
        //}
        //bool isPalindrome(int x) {
        //    if(x < 0){
        //        return false;
        //   }
        //    long long int newx = static_cast<long long int>(x);
        //    long long int reversex = reverse(x);
        //    if(newx == reversex){
        //        return true;
        //    }
        //    return false;
        //}
    
        //method 2: cut x into half
        bool isPalindrome(int x) {
            if(x < 0 || (x != 0 && x % 10 == 0)){
                return false;
            }   
            int half = 0;
            while(x > half){
                half = half * 10 + x % 10;
                x /= 10;
            }
            if(half == x || half / 10 == x){
                return true;
            }
            return false;
        }
    };

  • 0

    Same solution instead with Swift.... 228ms


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.