首页 > 其他 > 详细

[LeetCode] 9. Palindrome Number

时间:2016-08-05 11:40:36      阅读:195      评论:0      收藏:0      [点我收藏+]

 

#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);
}

 

[LeetCode] 9. Palindrome Number

原文:http://www.cnblogs.com/skyssky/p/5740361.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!