leetcode—迴文數
阿新 • • 發佈:2019-02-05
判斷一個整數是否是迴文數。不能使用輔助空間。
一些提示:
負整數可以是迴文數嗎?(例如 -1)
如果你打算把整數轉為字串,請注意不允許使用輔助空間的限制。
你也可以考慮將數字顛倒。但是如果你已經解決了 “顛倒整數” 問題的話,就會注意到顛倒整數時可能會發生溢位。你怎麼來解決這個問題呢?
利用陣列判斷,當輸入的數為負數時,不屬於迴文數class Solution { public: bool isPalindrome(int x) { int a[33]; int i = 0; if(x < 0) return false; while(x != 0) { a[i++] = x % 10; x /= 10; } int num = i; for(int j = 0; j < i; j++) { if(a[j] != a[--num]) return false; } return true; } };