9. 回文数

https://leetcode-cn.com/problems/palindrome-number/

 

 

 

虽然很简单,还是写一下题解吧。

思路1. 首先判断负数和个位数是0但x不等于0的一定不是回文。然后翻转字符串的一半,判断另一半时候和翻转后的相等。注意:121这种奇数位结构。

 1 public class Solution {
 2     public bool IsPalindrome(int x) {
 3         //首先负数/大于0并且个位数为0肯定不是回文。
 4         if(x < 0) return false;
 5         if(x == 0) return true;
 6         if(x % 10 == 0) return false;
 7         int  tmp = 0;
 8         while( x > tmp ) {
 9             tmp = tmp * 10 + x % 10;
10             x /= 10; 
11         }
12         return x == tmp || x == tmp / 10;
13     }
14 }
View Code

思路2.首先确定数字的位数,然后逐个判断第一位是否敌等于最后一位.....

 1 public class Solution {
 2     public bool IsPalindrome(int x) {
 3         if (x < 0){
 4             return false;
 5         }
 6         int a = 1;
 7         while (x / a >= 10){
 8             a *= 10;
 9         }
10         while(x != 0){
11             int left = x / a;
12             int right = x % 10;
13             if (left != right) return false;
14             x = x % a;
15             x /= 10;
16             a /= 100;
17         }
18         return true;
19     }
20 }
View Code

 

posted @ 2020-03-30 05:17  Quintinz  阅读(221)  评论(0编辑  收藏  举报