Leetcode Q9: Palindrome Number

题目9:

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

Some hints:

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?

There is a more generic way of solving this problem.

/***************************************************************************************************
*                    (c) Copyright 1992-2015 Embedded Products Research Center
*                                       All Rights Reserved
*
*\File          main.c
*\Description   Palindrome Number 判断一个数是否为回文
*\Note          
*\Log           2015.07.28    Ver 1.0    
*               创建文件。
***************************************************************************************************/
#include <stdio.h>
/***************************************************************************************************
*\Function      GetLen
*\Description   返回数x的十进制长度
*\Parameter     x
*\Return        int
*\Note          
*\Log           2015.07.28    Ver 1.0    
*               创建函数。
***************************************************************************************************/
int isPalindrome(int x) 
{
    int len = 1;        /* x十进制位数 */
    int left = 0;
    int right = 0;
    int temp_x = x;
    int max_mul = 1;
    int time = 0;

    /* 小于0判定为非回文 */
    if (x < 0)
    {
        return 0;
    }

    /* 一位数直接返回true */
    if (x >= 0 && x <= 9)
    {
        return 1;
    }

    /* 计算x十进制长度 */
    while (temp_x /= 10)
    {
        len++;
        max_mul *= 10;      
    }

    temp_x = x;

    /* 需要比较的次数 */
    time = len / 2;
    while (time)
    {
        /* 比较最高位和最低位是否相同 */
        left = temp_x / max_mul;        /* 获取最高位 */
        right = temp_x % 10;            /* 获取最低位 */
        if (left == right)
        {
            time--;
            temp_x = temp_x % max_mul;  /* 去掉最高位 */
            temp_x = temp_x / 10;       /* 去掉最低位 */
            max_mul /= 100;
        }
        else
        {
            return 0;
        }
    }
    return 1;
}

void main()
{
    int x = 123321;
    printf("%d\n", (isPalindrome(x)?1 : 0));
    getchar();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值