zoukankan      html  css  js  c++  java
  • [LeetCode#9] Palindrome Number

    The questions: 

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

    Analysis: 

    To determine whether an integer is a palindrome, we could try following ways:

    1. reverse the num into num', test iff num == num'.  (This method may encounter complex overlfow handle)

    2. use two pointer : front and end. Compare the digit at front and end, then move on !

    Skill:

    1. chop off the first digit, use '%'

    e: num = 65321,  num' = num % 10000=65321 % 10000 = 5321, then the first digit was chopped off

    2. chop off the last digit, use '/'

    e: num = 65321,  num' = num / 10 = 6532, then the last digit was chopped off

    Note: it's different from we want to get the first digit and last digit.

    1. get the first digit, use "/"

    e: num = 65321,  digit = num / 10000=65321 / 10000 = 6

    2. get the last digit, use "%"

    e: num = 65321,  num' = num % 10 = 2

    My solution: 

    public class Solution {
        public boolean isPalindrome(int x) {
            
              if (x < 0)
                return false; 
                
            int front_digit = 0;
            int end_digit = 0;
            int remain_number = x; 
            int number_size = number_digit_size(x);
            int digit_left = number_size;
      
            while (digit_left > 1) {
                
                front_digit = remain_number / power_of_ten(digit_left - 1);
                end_digit = remain_number % 10;
                
                if (front_digit != end_digit) {
                    return false; 
                }
                remain_number = remain_number % power_of_ten(digit_left - 1);//chop the first digit of the number
                remain_number = remain_number / 10; //chop the last digit of the number 
                
                digit_left = digit_left - 2;
            }
            
            return true;
        }
    
        static int power_of_ten(int count) {
            //return 10 ^ count
            int ret = 1;
            do {
                ret = ret * 10;
                count --; 
            } while (count > 0);
        
            return ret;
        }
    
        static int number_digit_size(int number) {
            //get the size of digits in the number
            int size = 0;
            if (number == 0)
            {
                return 1;
            }
        
            while (number != 0)
            {
                number = number / 10;
                size ++; 
            }
        
            return size; 
        }
    }
  • 相关阅读:
    CF-1102E-Monotonic Renumeration
    判断一颗二叉树是否为二叉搜索树
    Trie树的插入,查前缀,查单词,删前缀和删单词。
    poi 生成图片到excel
    poi 生成excel,最简单代码
    poi 实战代码---导出Excel(根据模板导出)
    共分为六部完成根据模板导出excel操作
    导入报版本不匹配问题
    ftp工具类
    关于获取路径path
  • 原文地址:https://www.cnblogs.com/airwindow/p/4192747.html
Copyright © 2011-2022 走看看