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);     }}
相关推荐
QT 小鲜肉12 小时前
【C++基础与提高】第十一章:面向对象编程进阶——继承与多态
java·linux·开发语言·c++·笔记·qt
aerror13 小时前
将sqlite3的表转成excel表
java·sqlite·excel
仟濹13 小时前
IntelliJ IDEA 快捷键 + 实时模板
java·intellij-idea
洛_尘13 小时前
数据结构--6:优先级队列(堆)
java·数据结构
大飞哥~BigFei13 小时前
RabbitMq消费消息遇到的坑
java·rabbitmq·java-rabbitmq
隐形喷火龙13 小时前
Springboot集成OnlyOffice
java·spring boot·后端
5pace13 小时前
【SSM|第一篇】MyBatisPlus
java·spring boot·后端·mybatis
JosieBook14 小时前
【SpringBoot】37 核心功能 - 高级特性- Spring Boot 中的 自定义 Starter 完整教程
java·spring boot·后端
小二·14 小时前
Elasticsearch 面试题精编(26题|含答案|分类整理)
java·大数据·elasticsearch