Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Follow up: Could you solve it without converting the integer to a string? 回文数字
Example 1: Input: x = 121 Output: true
Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Example 4: Input: x = -101 Output: false
Constraints:
-231 <= x <= 231 - 1
class Solution { public boolean isPalindrome(int x) { if(x==0){ return true; } //如果是负数则不是回文数字,如果是两位数 if(x<0||x%10==0){ return false; } int reverse_int=0; while(x>reverse_int){ int pop=x%10; x/=10; reverse_int=(reverse_int *10)+pop; } if(x==reverse_int ||x==reverse_int /10){ return true; }else{ return false; } } }自己的编译器下: 思路: x为要判断的值: 然后比如x=123321 在while循换下,条件是x<reverse_int,最后x=123,revers_int =123: 过程是: x每次x/10就每次x就去掉最后一位 而reverse_int就是x%10+之前的,也就是revere_int每次取最后一位并且随着顺序变成数字比如上面的从 1 -> 12->123. 最后退出循环发现x==reverse_int,那就是回文数【偶数的情况下】 【如果是奇数:比如x=121】 那么: x: 12 ->1 reverse_int : 1->12 x<reverse_int退出循环 把reverse_int /10=1 此时reverse_int ==x,so 121为回文数
再比如:x:1445 第一次循环: reverse_int =144 x=5 第二次循环: reverse_int =14 x=54 然后x>reverse_int,退出循环 but x!=reverse_int,所以不是回文数
package com.company; import java.util.Locale; import java.util.Scanner; public class 回文数字9{ public static Boolean isPakindrome(int x){ if (x==0){ return true; } if (x<0||x%10==0){ return false; } //1 2 3 3 2 1 // x:122332 1233 123 //reverse_int: 1 12 123 // 1 2 1 //x:12 1 //reverse_int:1 12 int reverse_int =0; while (x>reverse_int){ int pop=x%10; x/=10; reverse_int=(reverse_int *10)+pop; } if(x==reverse_int || x==reverse_int /10){ return true; }else { return false; } } public static void main(String[] args) { int x; while (true) { Scanner scanner = new Scanner(System.in); x = scanner.nextInt(); System.out.println(isPakindrome(x)); } } }