zoukankan      html  css  js  c++  java
  • palindrome number

    1. Question

    确定一个数是否是回文数。要求不使用额外空间。

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

    2. Solution

    如果是负数,就不是回文数。

    2.1 reverse integer

    采用反转整数的方法,注意处理溢出(采用long存储数据)

    public class Solution {
        public boolean isPalindrome(int x) {
            if( x < 0 )
                return false;
            long rev = 0;
            int y = x;
            while( y != 0 ){
                rev = rev * 10 + y % 10;
                y = y / 10;
            }
            if( rev == (long)x )
                return true;
            return false;
        }
    }
    View Code

    2.2 整除取余计算

    结合采用整除取余,同时从数的两端开始计算来判断(需要先确定位数)

    public class Solution {
        public boolean isPalindrome(int x) {
            if( x < 0 )
                return false;
            int bits = 1;
            for( int y=x/10; y!=0; y/=10,bits++ );
            for( int i=1; i<=bits/2; i++ ){
                if( ( ( x / (int)Math.pow( 10, bits-i ) ) % 10 )  != ( ( x / (int)Math.pow( 10, i-1 ) ) % 10 ) )
                    return false;
            }
            return true;
        }
    }
    View Code

    3. 复杂度

    O(n)

  • 相关阅读:
    文件输出debug
    sweetalert
    js认清this的第一步
    Creating default object from empty value in PHP?
    matplotlib画图
    python解析库
    zabbix监控ssl证书过期时间
    aws 预留实例到期监控
    aws ec2挂载 s3
    aliyun挂载oss
  • 原文地址:https://www.cnblogs.com/hf-cherish/p/4596321.html
Copyright © 2011-2022 走看看