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);     }}
相关推荐
极光代码工作室25 分钟前
基于SpringBoot的校园论坛系统
java·springboot·web开发·后端开发
XS03010638 分钟前
Spring Bean 作用域 & 生命周期
java·后端·spring
NagatoYukee39 分钟前
Spring Security基础部分学习
java·学习·spring
彦为君39 分钟前
JavaSE-07-异常机制
java·开发语言·后端·python·spring
_Aaron___2 小时前
Spring AI 接入 MCP:工具调用不是“能调就行”,关键是边界治理
java·人工智能·spring
向量引擎2 小时前
从零起步,如何打造专属向量引擎 API 中转工作流?
java·服务器·前端
LJianK12 小时前
普通接口,用到getter和setter方法的地方,jackson转换
java
辰海Coding2 小时前
MiniSpring框架学习-分解 Dispatcher
java·学习·spring·架构
AI人工智能+电脑小能手2 小时前
【大白话说Java面试题 第84题】【Mysql篇】第14题:为什么用 InnoDB 存储引擎的表建议用整型的自增主键?
java·开发语言·数据库·mysql·面试
小江的记录本2 小时前
【JVM虚拟机】JVM调优:常用JVM参数、调优核心指标、OOM排查、GC日志分析、Arthas工具使用(附《思维导图》+《面试高频考点清单》)
java·jvm·spring boot·后端·python·spring·面试