摘要:逐位看官,這兩種解法一看便知,小子便不多費唇舌了。字符數(shù)組比較法原數(shù)翻轉(zhuǎn)比較法
Problem
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)
NO
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.
Note逐位看官,這兩種解法一看便知,小子便不多費唇舌了。
Solution 字符數(shù)組比較法public class Solution { public boolean isPalindrome(int x) { if (x >= Integer.MAX_VALUE || x < 0) return false; int digit = 0, x2 = x; while (x2 != 0) { x2 /= 10; digit++; } int[] A = new int[digit]; while (x != 0) { A[--digit] = x % 10; x /= 10; } int left = 0, right = A.length-1; while (left < right) { if (A[left++] != A[right--]) return false; } return true; } }原數(shù)翻轉(zhuǎn)比較法
public class Solution { public boolean isPalindrome(int x) { if (x < 0) return false; long rvs = 0; int i = 0, org = x; while (x != 0) { i = x % 10; rvs = rvs * 10 + i; x /= 10; } return rvs == org; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/64784.html
Problem Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121Output: trueExample 2: Input: -121Output: falseExplana...
摘要:比較簡單的一道題目,用取模取余的方法求翻轉(zhuǎn)后的整數(shù)和原來的整數(shù)進行比較就行不用完全翻轉(zhuǎn),翻轉(zhuǎn)一半就可這已經(jīng)是最快的方法了 Easy 009 Palindrome Number Description: Determine whether an integer is a palindrome. An integer is a palindrome when it reads the sa...
摘要:首尾比較法復雜度時間空間,為所求的長度思路先求記為的長度根據(jù)長度制造掩碼循環(huán)當當最高位等于最低位還有數(shù)字等待判斷最高位通過掩碼和整除取得,最低位通過取余取得判斷過后更新掩碼,刪掉最高位,刪掉最低位注意求長度的如何取得一個的最高位假設答設置一 Palindrome Number Determine whether an integer is a palindrome. Do this w...
摘要:反轉(zhuǎn)比較法復雜度時間空間思路回文數(shù)有一個特性,就是它反轉(zhuǎn)后值是一樣的。代碼逐位比較法復雜度時間空間思路反轉(zhuǎn)比較有可能會溢出,但我們遍歷每一位的時候其實并不用保存上一位的信息,只要和當前對應位相等就行了。首先,負數(shù)是否算回文。 Palindrome Number Determine whether an integer is a palindrome. Do this witho...
摘要:題目分析這是上的第題,難度為,判斷整型數(shù)字是否為回文串,需要注意兩點負數(shù)都不是回文小于的非負整數(shù)都是回文這一題與第題類似,也可以有兩種思路數(shù)組法和模十法。所以代碼可以如下改進能被整除的非整數(shù)和負數(shù),返回 題目 Determine whether an integer is a palindrome. Do this without extra space. 分析 這是leetcode上...
摘要:有一點需要注意的是,負數(shù)不算作回文數(shù)。而第題當時的方法是,對整數(shù)取除的余數(shù),即是當前整數(shù)的最后一位。那么它翻轉(zhuǎn)后一半的數(shù)字之后,應該和前半段的數(shù)字相等,我們將采用這種思路進行解題。 題目詳情 Determine whether an integer is a palindrome. Do this without extra space.題目要求我們在不占用額外空間的前提下,判斷一個整...
閱讀 647·2021-11-24 09:39
閱讀 3489·2019-08-30 15:53
閱讀 2528·2019-08-30 15:44
閱讀 3247·2019-08-30 12:54
閱讀 2216·2019-08-29 12:23
閱讀 3312·2019-08-26 14:05
閱讀 2113·2019-08-26 13:36
閱讀 3445·2019-08-26 13:33