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);     }}
相关推荐
小林学习编程37 分钟前
SpringBoot校园失物招领信息平台
java·spring boot·后端
撸码到无法自拔38 分钟前
docker常见命令
java·spring cloud·docker·容器·eureka
蓝婷儿42 分钟前
前端面试每日三题 - Day 32
前端·面试·职场和发展
heart000_11 小时前
IDEA 插件推荐:提升编程效率
java·ide·intellij-idea
ŧ榕树先生2 小时前
查看jdk是否安装并且配置成功?(Android studio安装前的准备)
java·jdk
未来的JAVA高级开发工程师2 小时前
适配器模式
java
LUCIAZZZ2 小时前
JVM之内存管理(一)
java·jvm·spring·操作系统·springboot
D_aniel_2 小时前
排序算法-计数排序
java·排序算法·计数排序
极小狐2 小时前
极狐GitLab 通用软件包存储库功能介绍
java·数据库·c#·gitlab·maven
旧故新长2 小时前
Browserless 快速上手
java