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);     }}
相关推荐
DKPT2 分钟前
Java内存区域与内存溢出
java·开发语言·jvm·笔记·学习
资深前端之路4 分钟前
react 面试题 react 有什么特点?
前端·react.js·面试·前端框架
sibylyue7 分钟前
Guava中常用的工具类
java·guava
奔跑吧邓邓子11 分钟前
【Java实战㉞】从0到1:Spring Boot Web开发与接口设计实战
java·spring boot·实战·web开发·接口设计
拉不动的猪16 分钟前
回顾vue中的Props与Attrs
前端·javascript·面试
专注API从业者20 分钟前
Python/Java 代码示例:手把手教程调用 1688 API 获取商品详情实时数据
java·linux·数据库·python
奔跑吧邓邓子41 分钟前
【Java实战㉝】Spring Boot实战:从入门到自动配置的进阶之路
java·spring boot·实战·自动配置
ONLYOFFICE41 分钟前
【技术教程】如何将ONLYOFFICE文档集成到使用Spring Boot框架编写的Java Web应用程序中
java·spring boot·编辑器
叫我阿柒啊1 小时前
Java全栈开发工程师的实战面试经历:从基础到微服务
java·微服务·typescript·vue·springboot·前端开发·后端开发
cyforkk1 小时前
Spring 异常处理器:从混乱到有序,优雅处理所有异常
java·后端·spring·mvc