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);     }}
相关推荐
苹果醋31 小时前
React源码02 - 基础知识 React API 一览
java·运维·spring boot·mysql·nginx
Hello.Reader1 小时前
深入解析 Apache APISIX
java·apache
菠萝蚊鸭1 小时前
Dhatim FastExcel 读写 Excel 文件
java·excel·fastexcel
旭东怪2 小时前
EasyPoi 使用$fe:模板语法生成Word动态行
java·前端·word
007php0072 小时前
Go语言zero项目部署后启动失败问题分析与解决
java·服务器·网络·python·golang·php·ai编程
∝请叫*我简单先生2 小时前
java如何使用poi-tl在word模板里渲染多张图片
java·后端·poi-tl
ssr——ssss2 小时前
SSM-期末项目 - 基于SSM的宠物信息管理系统
java·ssm
一棵星2 小时前
Java模拟Mqtt客户端连接Mqtt Broker
java·开发语言
鲤籽鲲3 小时前
C# Random 随机数 全面解析
android·java·c#
zquwei3 小时前
SpringCloudGateway+Nacos注册与转发Netty+WebSocket
java·网络·分布式·后端·websocket·网络协议·spring