• 【LeetCode】9. Palindrome Number


    Difficulty: Easy

     More:【目录】LeetCode Java实现

    Description

    Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

    Example 1:

    Input: 121
    Output: true
    

    Example 2:

    Input: -121
    Output: false
    Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
    

    Example 3:

    Input: 10
    Output: false
    Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
    

    Follow up:

    Coud you solve it without converting the integer to a string?

    Intuition

    遇到数字的题目一定要考虑到正负数和0,以及溢出的情况。

    思路一:最开始想到的思路,翻转数字,与原来的数字比较,相等即可。对于溢出的情况,翻转后的数字和原来数字也不会相等,不会有影响。但是对于非Java语言的话,这种方法可能不行。

    思路二:还是翻转数字,但是只翻转一半,这翻转的一半与剩下的一半进行比较,例如:123321,后半部分翻转为123,与前半部分123相等即OK。这里要特别注意的是:奇数情况以及个位数为0的情况。例如:12321,123210

    思路三:获取最高位和最低位的数字,从两边数字向中间比较。

    Solution

    	//思路一:翻转数字(非Java语言可能不行)
    	public boolean isPalindrome1(int x) {
    	        if(x<0)	return false;
    			int m=x;
    			int n=0;
    			while(m!=0) {
    				n=n*10+m%10;
    				m/=10;
    			}
    			return n==x;
    	}
    	 
    	 
    	//思路二:翻转一半
        public boolean isPalindrome2(int x) {
            if(x<0)	return false;
            if(x!=0 && x%10==0) return false;   //防止个位数为0时误判为true。例如10
            int n=0;
    		while(x>n) {
    			n=n*10+x%10;
    			x/=10;
    		}
    		return n==x || x==n/10;
        }
        
        //思路三:最高位和最低位数字比较
        public boolean isPalindrome3(int x) {
            if(x<0)	return false;
    		int div=1;
    		while(x/div>=10)
    			div*=10;
    		while(x!=0) {
    			if((x%10)!=(x/div))	return false;
    			x=(x%div)/10;
    			div/=100;
    		}
    		return true;
        }
    

      

    What I've learned

    1. 遇到回文要想到:

      A.翻转后相等;

      B.前后对应位置相等;

      C.翻转一半后相等,但是要注意到奇偶数和个位为0的情况。

    2.和数字有关时,要注意:正负零,越界。

    3.掌握好如何获取数字最高位的方法。

     More:【目录】LeetCode Java实现

  • 相关阅读:
    tensorflow之tf.meshgrid()
    Python中数据的保存和读取
    透视投影推导
    tensorflow之tf.slice()
    tensorflow的tf.train.Saver()模型保存与恢复
    偶数分割求平均值
    母牛的故事
    统计一行的不重复的单词字符个数
    N个顶点构成多边形的面积
    贪心法基本入门
  • 原文地址:https://www.cnblogs.com/yongh/p/10165226.html
Copyright © 2020-2023  润新知