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);     }}
相关推荐
一 乐2 分钟前
健康管理|基于springboot + vue健康管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端·学习
是三好4 分钟前
分布式事务seata
java·分布式·seata
予枫的编程笔记6 分钟前
深度拆解美团后端一面:从压测体系到 JVM 调优的闭环面试艺术
jvm·面试·职场和发展·java面试·美团面试
为什么要做囚徒32 分钟前
多线程基础系列-线程死锁
java·多线程
bluetata37 分钟前
在 Spring Boot 中使用 Amazon Textract 从图像中提取文本
java·spring boot·后端
黎雁·泠崖1 小时前
Java底层探秘入门:从源码到字节码!方法调用的中间形态全解析
java·开发语言
we1less1 小时前
[audio] AudioTrack (六) 共享内存使用分析
java·开发语言
CYTElena1 小时前
关于JAVA异常的笔记
java·开发语言·笔记·语言基础
YIN_尹1 小时前
【C++11】lambda表达式(匿名函数)
java·c++·windows
猴子年华、1 小时前
【每日一技】:SQL 常用函数实战速查表(函数 + 场景版)
java·数据库·sql·mysql