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);     }}
相关推荐
IAUTOMOBILE2 分钟前
Code Marathon 项目源码解析与技术实践
java·前端·算法
Flying pigs~~2 分钟前
基于Deepseek大模型API完成文本分类预测功能
java·前端·人工智能·python·langchain·deepseek
Lyyaoo.3 分钟前
【JAVA基础面经】深拷贝与浅拷贝
java·开发语言·算法
oyzz1209 分钟前
Redis 安装及配置教程(Windows)【安装】
java
YNCAH_16 分钟前
特殊类的设计
java·开发语言
studyForMokey21 分钟前
【Android面试】Fragment生命周期专题
android·microsoft·面试
商吉婆尼21 分钟前
天地图API调用注意事项
java·spring·天地图
芒果披萨30 分钟前
sql存储过程
java·开发语言·数据库
yaoxin52112337 分钟前
368. Java IO API - 基本文件属性
java·开发语言·python
_日拱一卒42 分钟前
LeetCode:最小覆盖字串
java·数据结构·算法·leetcode·职场和发展