Palindrome Number leetcode java
发布日期:2025-05-01 14:44:17 浏览次数:2 分类:技术文章

本文共 1694 字,大约阅读时间需要 5 分钟。

题目

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.

 

题解

 最开始是用Reverse Integer的方法做的,通过了OJ,不过那个并没有考虑越界溢出问题。遇见这种处理Number和Integer的问题,首要考虑的就是会不会溢出越界。然后再考虑下负数,0。还有就是要心里熟悉\的结果和%的结果。感觉这种题就是考察你对数字敏感不敏感(反正我是很不敏感)

 有缺陷的代码如下:

 

 1     
public 
boolean isPalindrome(
int x) {
 2         
if(x<0)
 3            
return 
false;
 4         
 5         
int count = 0;
 6         
int testx = x;
 7         
while(testx!=0){
 8            
int r = testx%10;
 9            testx = (testx-r)/10;
10            count++;
11         }
12         
13         
int newx = x;
14         
int result = 0;
15         
while(newx!=0){
16            
int r = newx%10;
17            
int carry = 1;
18            
int times = count;
19            
while(times>1){
20                carry = carry*10;
21                times--;
22            }
23            result = result+r*carry;
24            newx= (newx-r)/10;
25            count--;
26         }
27         
28         
return result==x;
29         
30     }

 

另外一种方法可以避免造成溢出,就是直接安装PalidromeString的方法,就直接判断第一个和最后一个,循环往复。这样就不会对数字进行修改,而只是判断而已。

代码如下:

 1     
public 
boolean isPalindrome(
int x) {
 2         
//
negative numbers are not palindrome
 3 
        
if (x < 0)
 4             
return 
false;
 5  
 6         
//
 initialize how many zeros
 7 
        
int div = 1;
 8         
while (x / div >= 10) {
 9             div *= 10;
10         }
11  
12         
while (x != 0) {
13             
int left = x / div;
14             
int right = x % 10;
15  
16             
if (left != right)
17                 
return 
false;
18  
19             x = (x % div) / 10;
20             div /= 100;
21         }
22  
23         
return 
true;
24     }

 Reference:

http://www.programcreek.com/2013/02/leetcode-palindrome-number-java/

 

转载于:https://www.cnblogs.com/springfor/p/3889214.html

上一篇:Palo Alto Networks Expedition 未授权SQL注入漏洞复现(CVE-2024-9465)
下一篇:paip.spring3 mvc servlet的配置以及使用最佳实践

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年04月06日 22时40分43秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章