leetcode-Palindrome Number

本文探讨了LeetCode上两道关于回文数的问题,详细介绍了两种解题思路及其实现代码。第一种方法通过反转数字进行比较,第二种方法则通过对比最高位和最低位数字来判断是否为回文数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode的easy层次都是一些简单题,一些有递进的简单题。譬如第七题和第九题,方法都是一样,取模整除再相乘,但是第九题有一点不一样的是,第七题已知,取模对正数和负数都一样,但是在第九题的回文数字中,却要求翻转过的数字跟原数字一模一样。如下:

这里是引用
Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -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:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
解题思路:按照回文数字的要求,负数是不可能的,所以剔除负数,再按照取模的方式。代码如下;

  1. List item
    class Solution {
    public boolean isPalindrome(int x) {
    if(x<0)
    return false;
    int num=0,b=0,pre=x;
    while(pre!=0)
    {
    b=pre%10;
    num=num*10+b;
    pre=pre/10;
    }
    if(num==x)
    篮子王的视频return true;
    else
    return false;

第二种思路:
算出这个数是几位数,再循环取出它的最高位数和最低位数,看是否相等,如果相等,则true,若中间有不等的部分,则返回false。代码如下:
2. public class Solution{
3. public boolean isPalindrome(int x){
4. if(x<0) return false;
5. int div=1;
6. int num=x;
7. while(num/div>=10){ //算出这个数有几位
8. div*=10;
9. }
10. whlie(num!=0){
11. int left=num/div;
12. int right=num%10;
13. if(left != right)
14. return false;
15. num=(num-left*div)/10;
16. div/=100;
17. }
18. return true;
19. }
20. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值