• No.9 Palindrome Number


    No.9 Palindrome Number

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

    click to show spoilers.

    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.

     1 class Solution
     2 {
     3 public:
     4     bool isPalindrome(int x)
     5     {//判断整数是否为回文
     6      //限制:不允许使用额外空间
     7      //提示:负数是否为回文?;不能转换为string,因为不允许使用额外空间;反转数字的话,有可能溢出
     8      //用纯数学的方法,想清楚就好,别慌,敢下手!!!
     9      //参考:http://blog.csdn.net/linhuanmars/article/details/21145231
    10         if(x < 0)
    11             return false;//负数不是回文
    12         if(x == 0)
    13             return true;
    14 
    15         int base = 1;//用于取高位
    16         while(base <= x/10)
    17             base *= 10;
    18 
    19         while(x>0)
    20         {
    21             if(x/base != x%10)
    22                 return false;
    23 
    24             x = (x%base)/10;//去首去尾
    25             base /= 100;//每次消去两位
    26         }
    27         return true;
    28     }
    29 };
     1 class Solution
     2 {
     3 public:
     4     bool isPalindrome(int x)
     5     {//判断整数是否为回文
     6      //限制:不允许使用额外空间
     7      //提示:负数是否为回文?;不能转换为string,因为不允许使用额外空间;反转数字的话,有可能溢出
     8      //参考:http://www.cnblogs.com/remlostime/archive/2012/11/13/2767676.html
     9         if(x < 0)
    10             return false;//负数不是回文
    11         if(x == 0)
    12             return true;
    13 
    14         int base = 1;//用于取高位
    15         while(base <= x/10)
    16             base *= 10;
    17 
    18         int leftDigit ;
    19         int rightDigit ; 
    20         while(x)
    21         {
    22             leftDigit = x/base;
    23             rightDigit = x%10;
    24             if(leftDigit != rightDigit)
    25                 return false;
    26 
    27             x -= base*leftDigit;//去首
    28             base /= 100;//每次消去两位
    29             x /= 10;//去尾
    30         }
    31         return true;
    32     }
    33 };
    View Code
  • 相关阅读:
    HDU1998奇数阶魔方 一个好玩的程序 按规则写蛮简单的
    ASCII码表
    排序之快速排序算法
    HDU1002 A + B Problem II
    SDUT2136数据结构实验之二叉树的建立与遍历
    (转)计算组合数整数拆分
    IE CSS Bug及解决方案参考手册
    包含空格的项目的文件/路径部分需要用括号括起来
    Ext学习笔记07 Window及Window中的布局
    Google Map 2.0 获取当前倍率和当前点击所在地理坐标
  • 原文地址:https://www.cnblogs.com/dreamrun/p/4569288.html
Copyright © 2020-2023  润新知