LeetCode刷题1

in 力扣 with 1978 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. flomax uk cost

    Reply
  2. modafinil paypal

    Reply
  3. important link how to get hacks in roblox

    Reply
  4. generic lyrica online

    Reply
  5. otc dexamethasone

    Reply
  6. lyrica canada cost

    Reply
  7. Записаться на прием к урологу Москва cecilplus.ru

    Сейчас медицина в РФ развивается молниеносно. Это весьма хорошо, но также открылось много поликлиник, которые оказывают спорные услуги. Хотим познакомить Вас с клиникой «Сесиль», которая осуществляет работу уже более 20-ти лет, имеет превосходную репутацию и штат настоящих профессионалов.

    Что касается запись к урологу мы Вам с легкостью окажем помощь. Предлагаем консультации, программное лечение и диагностику по различным направлениям. В том числе: гинекология, кардиология, невролгия-вегетология, урология, педиатрия и многие другие. По оставшимся вопросам звоните по номеру телефона +7(499)302-63-62 или оформите обратный звонок на веб сайте cecilplus.ru уже сегодня. Ещё присутствует онлайн запись и оплата приема для Вашего комфорта.

    Мы расположены по адресу: г. Москва, ул. Чаплыгина, д. 6, м. Чистые пруды. Время работы с понедельника по субботу с 9:00 до 21:00. Вдобавок на указанном сайте Вы можете посмотреть цены на наши услуги. Некоторые услуги могут быть представлены с выездом на Ваш адрес, необходимо уточнить у специалиста.

    Если Вы хотели найти электроэнцефалограмма в сети интернет, то вы на правильном пути. Наши врачи на cecilplus.ru непременно Вам окажут помощь, ведь у них большой опыт и регулярные повышения квалификации. Будем рады Вам помочь обрести здоровое тело, побороть болезнь и жить счастливой жизнью!

    Reply
  8. where to buy acyclovir cream over the counter

    Reply
  9. Park City Mountain Resort. Good, Christopher.

    "Vail buys Park Metropolis Mountain Resort for $182M".
    When the acquisition was finalized, Vail added Park Metropolis
    Mountain Resort to its EPIC season pass program for the 2014-15 season.
    Paskin, Janet. "The Ski Resort Battle Over Park Metropolis Mountain".
    Park City mountain resort is dwelling to many ski colleges run by
    the mountain, however is also home to privately owned ski
    schools. In March 2012, Powdr Company (POWDR), homeowners of Park City
    Mountain Resort (PCMR), announced that it had filed
    a lawsuit against Talisker Land Holdings, LLC
    (Talisker), which owned the adjacent Canyons Resort, as well
    as United Park City Mines Firm, each partial land owners of the resort.
    Eight months later, POWDR acquired a letter from Talisker that their
    lease had expired and so they have been to turn over the leased
    land and its improvements to Talisker. POWDR sued Talisker for $7 million (equivalent to $9.3 million in 2023) for compensatory
    and punitive damages for the menace of the closure of the resort.
    On September 11, 2014, Vail introduced that it had
    purchased the bottom of PCMR, including its name and recognition of ski runs improvements, from POWDR for $182.5 million (equal
    to $234.9 million in 2023) and that it will combine the resort with neighboring Canyons Resort over the summer of 2015 for the 2015-sixteen season.

    Reply
  10. Are you up for a road trip? Automobile Life said the OHC six was "commendably smooth and quiet." Its
    testers recorded a 0-60-mph time of 15.9 seconds with automatic and 17 mpg on a 60-mph
    freeway trip. 70s. See extra classic car pictures. Can you see the 3-D aspect?
    What's one other toy that may be utilized in professional
    arenas? The toy on the subsequent web page is from a Danish
    firm. For any company with an intensive catalog of merchandise, this app is
    obligatory. Nike as a result of ample benefit years
    demand for sports activities and leisure shoes for the elderly, understand their way of life and ideals of hope, out
    demands famous with progressive new merchandise, communicate and promotional actions, from starting to finish is a station in creating shopper trend of Pai Tau, first on the planet
    not have unearned status of Nike. Yo-yos are one in every of the most popular toys round, even after
    a whole lot of years. On the next web page, see one of the first toys that produced 3-D photographs.
    Numerous video games are available as apps on smartphones and tablets,
    making them widespread toys for children and adults alike.
    The Transformers toy line has been entertaining children for over two many years.

    Reply