LeetCode Top Interview 150

Math

Q****9. Palindrome Number

Given an integer x, return trueif x is a palindrome, and false otherwise.

Example 1:

vbnet 复制代码
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

vbnet 复制代码
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

vbnet 复制代码
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Constraints:

  • -231 <= x <= 231 - 1

Follow up: Could you solve it without converting the integer to a string?

解法及注释:

sql 复制代码
class Solution {    public boolean isPalindrome(int x) {        //pre-check        if(x < 0 || x > Math.pow(2,31)-1 || (x != 0 && x %10 == 0 )) {            return false;        }        if(x < 10) {            return true;        }         return useString(x);        //return useMath(x);    }    private boolean useString(int x) {        String s = String.valueOf(x);        int n = s.length();        for(int i = 0; i < n/2; i++) {            if(s.charAt(i) != s.charAt(n-i-1)) {                return false;            }        }        return true;    }    private boolean useMath(int x) {        int rev = 0;        while(x > rev) {            rev = rev * 10 + x % 10;            x /= 10;        }        return (x == rev || x == rev/10);     }}
相关推荐
sunny_5 小时前
面试踩大坑!同一段 Node.js 代码,CJS 和 ESM 的执行顺序居然是反的?!99% 的人都答错了
前端·面试·node.js
NE_STOP6 小时前
MyBatis-配置文件解读及MyBatis为何不用编写Mapper接口的实现类
java
ayqy贾杰7 小时前
Agent First Engineering
前端·vue.js·面试
Lee川10 小时前
解锁 JavaScript 的灵魂:深入浅出原型与原型链
javascript·面试
swipe10 小时前
从原理到手写:彻底吃透 call / apply / bind 与 arguments 的底层逻辑
前端·javascript·面试
后端AI实验室11 小时前
用AI写代码,我差点把漏洞发上线:血泪总结的10个教训
java·ai
程序员清风12 小时前
小红书二面:Spring Boot的单例模式是如何实现的?
java·后端·面试
belhomme13 小时前
(面试题)Redis实现 IP 维度滑动窗口限流实践
java·面试
Lee川13 小时前
探索JavaScript的秘密令牌:独一无二的`Symbol`数据类型
javascript·面试
Be_Better13 小时前
学会与虚拟机对话---ASM
java