classSolution { public: boolisPalindrome(int x){ if(x < 0) { returnfalse; } if(x == 0) { returntrue; } int base = 1; while(x / base >= 10) { base *= 10; } while(x) { int left = x / base; int right = x % 10; if(left != right){ returnfalse; } x -= base*left; base /= 100; x /= 10; } returntrue; } };
解决方案3(Golang)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
func isPalindrome(x int) bool { if x < 0 { return false } nums := []int {} for x != 0 { nums = append(nums, x%10) x /= 10 } length := len(nums) for i := 0; i < length/2; i++ { if nums[i] != nums[length-i-1] { return false } } return true }