1. 程式人生 > >leetcode-9.迴文數(水仙花數)

leetcode-9.迴文數(水仙花數)

leetcode-9.迴文數(水仙花數)

題意:給定整數,判斷是否是水仙花數(迴文數),返回判斷結果

演算法:

1.判斷負數, 如果是負數直接返回false
2.將整數逐位拆解,用陣列儲存
3.遍歷陣列,若本位與後面對應位不等返回false.

Code

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         if(x < 0)
 5             return false;//負數,直接返回false
 6         int perBit[32+2];//陣列,用於儲存數字每一位
7 int count=0; 8 bool flag = true; 9 while(x)//數字陣列化 10 { 11 perBit[count] = x%10; 12 x /= 10; 13 count++; 14 } 15 for(int i=0; i<count; i++)//遍歷陣列(其實是遍歷一般) 16 { 17 if(perBit[i] != perBit[count-1-i])//
對應位置值不等,不是,返回false 18 { 19 return false; 20 } 21 if(i == count/2)//掃一半就夠了 22 break; 23 } 24 return flag;//若是,返回true 25 } 26 };