LeetCode - Palindrome Number

发布时间:2017-3-27 1:04:21 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"LeetCode - Palindrome Number",主要涉及到LeetCode - Palindrome Number方面的内容,对于LeetCode - 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. public class Solution { public boolean isPalindrome(int x) { if(x < 0) return false; else if(x < 10) return true; int a[] = {0,0,0,0,0,0,0,0,0,0,0,0,0}; int b[] = {0,0,0,0,0,0,0,0,0,0,0,0,0}; double index = 0; double number1 = x; for(double i = 0;i < 13; i ++){ if(x >= Math.pow(10, i+1)){ a[(int) i] = (int) (number1 % 10); index = i; number1 = number1/10 ; // System.out.println(number1); } else{ a[(int) i] = (int) number1; break; } } for(double i = 0;i <= index + 1; i ++) b[(int) i] = (int) ((int)(x % Math.pow(10, index - i + 2))/Math.pow(10, index - i + 1)); int flag = 1; for(int j = 0;j <= index + 2; j ++){ // System.out.println("This is the "+ j + "th"+ a[j] + " " + b[j]); if(a[j] != b[j]) flag = 0; } if(flag == 0) return false; return true; } } 更好的解法: public class Solution { public boolean isPalindrome(int x) { //negative numbers are not palindrome if (x < 0) return false; // initialize how many zeros int div = 1; while (x / div >= 10) { div *= 10; } while (x != 0) { int left = x / div; int right = x % 10; if (left != right) return false; x = (x % div) / 10; div /= 100; } return true; } }

上一篇:追梦,听我给你讲一个农家女的故事
下一篇:判断远程文件是否存在

相关文章

相关评论

本站评论功能暂时取消,后续此功能例行通知。

一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!

二、互相尊重,对自己的言论和行为负责。

好贷网好贷款