LeetCode 9 迴文數 (Palindrome Number) —— 得到整形數的位數及尾數
阿新 • • 發佈:2018-12-22
這裡使用一種較笨的方法,適合初學者理解。
主要的過程就是用取餘操作得到最後一位,用除法操作得到一共有幾位。具體程式如下:
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
int n = 0;
long sum = 0;
int pos=x;
//得到位數和餘數
vector<int> y (32,0);
for(int i = 0; pos!= 0; ++i )
{
n++;
y[i] = pos%10;
pos /= 10;
}
//得到新數
for(int j = 0; j < n; j++ )
{
sum *= 10;
sum = sum + y[j];
}
printf("%d" ,sum);
if(sum == x)
return true;
return false;
}
};