LeetCode | 9. Palindrome Number (回文数)

题目

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

什么是回文数

来源于百度百科:回文数

“回文”是指正读反读都能读通的句子,它是古今中外都有的一种修辞方式和文字游戏,如“我为人人,人人为我”等。在数学中也有这样一类数字有这样的特征,成为回文数(palindrome number)。

设n是一任意自然数。若将n的各位数字反向排列所得自然数n1与n相等,则称n为一回文数。例如,若n=1234321,则称n为一回文数;但若n=1234567,则n不是回文数。

注意:

  1. 偶数个的数字也有回文数124421
  2. 小数没有回文数
  3. 负数不是回文数
  4. 一位数都是回文数

我的思路

  1. 通过除法和求余将数字的首尾两个数字提取出来并且进行对比;
  2. 通过减法和除法把首尾两个数字从原来的数中去掉。如:12421 变成 242;
  3. 重复步骤1、2,直到将数字的每个位都对比一遍。从而判断数字是否是回文数。

回文数例子

代码

bool isPalindrome(int x) {
  int digitCnt = 0;
  int n, i, k, resPower, remainder, quotient;

  // 负数不是回文数
  if (x < 0)
    return false;

  // 一位数都是回文数
  if (x >= 0 && x < 10)
    return true;

  // 得到数字 x 的位数
  k = x;
  do {
    digitCnt++;
    k = k / 10; 
  } while (k != 0);
  printf("The digit number of %d is %d.\n", x, digitCnt);

  k = digitCnt;
  for (n = 1; n <= (digitCnt / 2); n++) {
    resPower = 1;
    for (i = 0; i < (k - 1); i++) {
      resPower *= 10;
    }
    // x 的末位数字
    remainder = x % 10;
    // x 的首位数字
    quotient = x / resPower;

    printf("Loop: %d\n", n);
    printf("The rightmost digit is %d\n", remainder);
    printf("The leftmost digit is %d\n", quotient);

    // 比较首尾两位数字
    if (remainder != quotient)
      return false;

    // 删除 x 的首尾两位数字,得到新的数字 x。
    printf("Change x from %d ", x);
    x -= resPower * quotient;
    x /= 10;
    k -= 2;
    printf("to %d.\n", x);
  }

  return true;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值