LeetCode数学类(一)

今天又刷了两道数学类的easy题,虽然是easy题,但还是有点体会。

题目一

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

分析

刚开始的时候我是采取了先判断x的正负,根据颠倒之后是否变号来判断是否溢出的,结果证明这种方法有些case通不过。看了别人的代码才知道,原来可以通过定义long long int来解决这个问题,受教了。

代码

class Solution {
public:
    int reverse(int x) {
        long long int result=0;
        while(x!=0){
            result=result*10+x%10;
            x=x/10;
        }
        return (result<INT_MIN || result>INT_MAX) ? 0 : result;
    }
};

题目二

Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.

分析

这道题是让判断一个数是不是回文数的,很明显。负数是没有回文数的,能整除10的数字也是没有回文数的。刚开始我是想直接把一个数颠倒过来判断是否相等来计算的。结果发现比较慢,后来想到了其实并没必要全部判断,可以以颠倒到两者相等为分界点,也就是代码一中的(x>result)这一句话结束循环时x<=result。相等的情况就是1221这种回文数,不等的就是12321这种回文数。所以代码一写的很严谨。代码二是一种更高效的代码,它主要是采取了一种一位位比较,只要有一位不相等,立马就返回的方法。在某些不是回文数的判断上会比方法一快速。其中我也发现了LeetCode上的一个问题,相同的代码,每次运行的时间却相差比较大。如下图所示。

这里写图片描述

代码一

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0||(x!=0&&x%10==0)) 
            return 0;
        int result=0;
        while(x>result){
            result=result*10+x%10;
            x=x/10;
        }
        return (x==result)||(x==result/10);
    }
};

代码二

class Solution {
public:
    bool isPalindrome(int x){
       if(x<0) {
            return false;
        }
        int div = 1;
        while(div <= x/10)
            div *= 10;
        while(x>0){
            if(x/div != x%10)
                return false;
            x = (x%div)/10;
            div /= 100;
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值