1. 程式人生 > 其它 >【演算法題】【★】迴文數

【演算法題】【★】迴文數

技術標籤:筆試/面試演算法

//判斷一個整數是否是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數。 
//
// 示例 1: 
//
// 輸入: 121
//輸出: true
// 
//
// 示例 2: 
//
// 輸入: -121
//輸出: false
//解釋: 從左向右讀, 為 -121 。 從右向左讀, 為 121- 。因此它不是一個迴文數。
// 
//
// 示例 3: 
//
// 輸入: 10
//輸出: false
//解釋: 從右向左讀, 為 01 。因此它不是一個迴文數。


//leetcode submit region begin(Prohibit modification and deletion)
class Solution
{ public boolean isPalindrome(int x) { if (x < 0 || (x % 10 == 0 && x != 0)) return false; int n = 0; while (x > n) {//這裡僅需要比較一半即可,不需要x!=0 n = n * 10 + x % 10; x = x / 10; } return x == n || x == n / 10;//x == n是偶數位的情況,x == n/10是奇數位的情況
// if (x == 0) { // return true; // } // if (x < 0 || x % 10 == 0) { // return false; // } // int n = 0; // int a = x; // while (x != 0) { // n = n * 10 + x % 10; // x = x / 10; // } // if (a == n) { // return true;
// } else { // return false; // } } } //leetcode submit region end(Prohibit modification and deletion)