zoukankan      html  css  js  c++  java
  • Java [leetcode 9] 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.

    解题思路:

    首先判断是否为负数,若是负数,直接返回false。否则继续下面判断:

    从两头开始往中间读数,分别判断即可。

    代码如下:

    public class Solution {
       public boolean isPalindrome(int x) {
    		int divisor = 1;
    		int left;
    		int right;
    		int temp = x;
    		if (x < 0)
    			return false;
    		while (temp / 10 > 0) {
    			divisor *= 10;
    			temp = temp / 10;
    		}
    
    		while (x != 0) {
    			left = x / divisor;
    			right = x % 10;
    			if (left != right)
    				return false;
    			x = (x % divisor) / 10;
    			divisor = divisor / 100;
    		}
    		return true;
    	}
    }
    
  • 相关阅读:
    2
    网络对抗第四次实验恶意代码
    网络对抗第三次实验
    网络对抗第二次实验
    网络攻防第一次实验
    123
    数据结构
    第五次实验
    第二次实验
    Qt应用笔记
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4455861.html
Copyright © 2011-2022 走看看