• Leetcode | Palindrome Number


    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.

    直接的思路就是每次将最高位和最低位相比,直到只剩下0个或1个数字。

    要求最高位就必须要知道基数(10的n次方),每次取了最高位和最低之后,基数是要除以100的,当基数小于1的时候就不需要比较了。

    因为输入是int类型,求基数的时候要注意不要overflow。

    如果要以x / m > 0 来求基数的话,那么注意m要用long long类型。 不过最好是用 x /m >=10 来判断。

     1 class Solution {
     2 public:
     3     bool isPalindrome(int x) {
     4         if (x < 0) return false;
     5         if (x < 10) return true;
     6         int m = 1; // long long m = 1
     7         while (x / m >= 10) { //x / m > 0
     8             m *= 10;
     9         }
    10         //m /= 10;
    11         int l, r;
    12         while (m > 1) {
    13             l = x / m;
    14             x = x % m;
    15             m /= 100;
    16             r = x % 10;
    17             x = x / 10;
    18             if (l != r) return false;
    19         }
    20         
    21         return true;
    22     }
    23 };
  • 相关阅读:
    Consul常用命令
    ECharts 避免变窄
    TP3.2 日期默认格式
    新订单提示效果
    php 按照字典序排序 微信卡券签名算法用到
    td宽度自适应 窄的地方自动收缩
    git 删除本地分支,删除远程分支
    分页Model
    chrome表单自动填充如何取消
    tp3.2 如何比较两个字段
  • 原文地址:https://www.cnblogs.com/linyx/p/3702743.html
Copyright © 2020-2023  润新知