LeetCode 9. Palindrome Number
原题链接在这里:https://leetcode.com/problems/palindrome-number/
题目:Determine whether an integer is a palindrome. Do this without extra space.
题解:
div 表示能走到x的最高位. x/div就是x的最高位.
Note: In case of overflow, when calculating limit, while loop needs limit <= x/10, but not limit * 10 < x.
Since limit * 10 may be overflow already.
Time Complexity: O(digit), digit代表x共有多少位.
Space: O(1).
AC Java:
1 class Solution { 2 public boolean isPalindrome(int x) { 3 if(x < 0){ 4 return false; 5 } 6 7 int limit = 1; 8 while(limit <= x / 10){ 9 limit *= 10; 10 } 11 12 while(x > 0){ 13 if(x / limit != x % 10){ 14 return false; 15 } 16 17 x = (x % limit) / 10; 18 limit /= 100; 19 } 20 21 return true; 22 } 23 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步