LeetCode刷题1

in 力扣 with 3356 comments

题目描述

给你一个32位的有符号整数x,返回将x中的数字部分反转后的结果。
如果反转后整数超过32位的有符号整数的范围 [−2^31,2^31−1],就返回 0。
假设环境不允许存储64位整数(有符号或无符号)。


思路

1.数字反转
利用%和/,将x的最后一位数字提取出来,放到返回数字rev的最前面,由于是10进制整数,所以只要每次操作时*10进一位。

int digit = x % 10;// 提取最后一位数字
x /= 10;// x去除最后一位
rev = rev*10 + digit;// rev初始值为0,赋值给最终的数字

2.整数反转的范围限制

题目要求x是32位无符号整数,环境不允许存储64位整数
反转后整数超过32位的有符号整数的范围就返回0
官方思路
-2^31 <= rev * 10 + digit <= 2^31-1
不等式不成立则返回0
然后一堆花里胡哨数学操作ToT
推导成了
(-2^31)/10 <= rev <= (2^31-1)/10
写的乱主要是不会传图,划掉

//最终代码,这里INT_MIN和INT_MAX应该是c语言中定义的int型的最大最小值
int reverse(int x) {
    int rev = 0;
    while (x != 0) {
        if (rev < INT_MIN / 10 || rev > INT_MAX / 10) {
            return 0;
        }
        int digit = x % 10;
        x /= 10;
        rev = rev * 10 + digit;
    }
    return rev;
}

我的理解
在数字转化的过程中,只要x不为0,rev就会比原来的值大10倍+,即rev = rev*10 + digit,所以为了避免超出范围,只要将rev和极值的1/10进行比较(在x!=0的前提下)。
假如还需要缩小范围,可以1、极值/100;2、条件改为while(x/10 !=0),不过该情况下对于x==0要单独考虑

今日总结

  1. 对于算法这方面还有很多需要加强的地方,主要在于做题的思路方面,需要多加练习。
  2. C、Java的基础方面还很薄弱,需要加强,多加练习
  3. 中等难度的题目就一头雾水了[o(╥﹏╥)o],我可真菜
Responses / Cancel Reply
  1. Автостатьи https://tvregion.com.ua з продами з ремонту та телефона

    Reply
  2. Ежедневные автомобильные новости https://viewport.com.ua и статьи, тесты, характеристики авто и выбор машины

    Reply
  3. Все новые авто https://autoiceny.com.ua с подробными обзорами, фото и характеристиками на единственном сайте автомобильных тестов

    Reply
  4. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: ремонт крупногабаритной техники в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

    Reply
  5. We are a gaggle of volunteers and starting a brand new scheme in our community.
    Your site provided us with useful info to work on. You've performed
    a formidable process and our entire neighborhood can be
    grateful to you.

    Reply
  6. Если вы искали где отремонтировать сломаную технику, обратите внимание - ремонт бытовой техники в перми

    Reply
  7. Женский сайт https://onlystyle.com.ua семья, дети, красота и здоровье

    Reply
  8. Последние новости https://ua-novosti.info Украины и мира, политические и аналитические статьи, курсы валют, индексы и котировки, интервью, мнения, бизнес новости

    Reply
  9. Самые свежие новости https://onlystyle.com.ua красоты, моды, здоровья и прочее, что нужно женщинам

    Reply
  10. This isn't perfect since in the case of lingerie fit is crucial aspect.

    Designer lingerie is value the investment because these manufacturers specialize in designing lingerie that's not only fashionable but additionally ones that
    match to perfection and supply the help you want. The very best half is that for getting these equipment, you don't need the need to pay more
    as these are available in a worth range-pleasant price.
    Now that you know how to purchase plus measurement lingerie for your self,
    look online for stores providing reasonably priced plus measurement lingerie,
    plus dimension push up bras, and many others.
    Remember, lingerie plays an enormous part in how you carry yourself.
    Store our complete variety of plus size lingerie to seek out
    dreamy plus size babydolls, bodystockings, bras, bustiers,
    camisoles and extra. Listed listed here are a quantity of inside the concerns that incessantly come up from women after they're lingerie browsing, no matter if they can be in shops or looking for on the web, plus some solutions that may with any
    luck , make it easier to as a part of your lookup for simply the right kinds
    of lingerie. With a panty, it's just a matter of finding your favourite one as a way
    to stick to the type.

    Reply