[LeetCode] 9. Palindrome Number

 

#include <stdio.h>
#include <stdbool.h>
#include <math.h>

// 9. Palindrome Number
// Determine whether an integer is a palindrome. Do this without extra space.
// https://leetcode.com/problems/palindrome-number/

// Algorithm:
// get reverse of x => x'
// check whether x == x'
//         if yes, return true
//      else, return false

// Assume x >= 0
// Assume no '+'' or '-'' sign at front
// Assume no space

// base case: x < 10, return true

bool isPalindrome(int x) {
    // Base case
    if (x < 0) return false;    // negative number is NOT palindromic
    if (x < 10) return true;    // single digit is palindrome

    // Get reverse of x
    int y = 0, n = x;    
    while(n) {
        y = y * 10 + n % 10;
        n /= 10;
    }

    // if original x equals to its reverse, it is palindrome
    if (x == y) return true;

    return false;
}

int main() {
    int x = -2147447412;
    char *result = isPalindrome(x) > 0 ? "true" : "false";
    printf("*%d* is palindrome: %s\n", x, result);
}

 

posted @ 2016-08-05 10:43  兔纸不吃草  阅读(220)  评论(0编辑  收藏  举报