9.Palindrome Number

题目链接:https://leetcode.com/problems/palindrome-number/description/

题目大意:给定一个int范围的数字,判断是否是回文(要求不要额外开辟空间)。

法一:将int数字转为string,直接做。代码如下:

 1 public boolean isPalindrome(int x) {
 2         String s = String.valueOf(x);
 3         int len = s.length();
 4         for(int i = 0; i < len / 2; i++) {
 5             if(s.charAt(i) != s.charAt(len - i - 1)) {
 6                 return false;
 7             }
 8         }
 9         return true;
10     }
View Code

法二:倒计算,查看最后结果,是否相同,如果相同,则说明是回文。代码如下:

 1     public boolean isPalindrome(int x) {
 2         if(x < 0 || (x != 0 && x % 10 == 0)) {
 3             return false;
 4         }
 5         int res = 0;
 6         while(x > res) {
 7             res = res * 10 + x % 10;
 8             x /= 10;
 9         }
10         return (x == res || res / 10 == x);
11     }
View Code

 

posted on 2018-02-28 19:30  二十年后20  阅读(118)  评论(0编辑  收藏  举报

导航