LeetCode刷题1

in 力扣 with 1645 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
  1. Davidgok

    узнать больше https://futbolka-trenbolon.ru

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

    Reply
  3. Jefferypoick

    http://www.bisound.com/forum/showthread.php?p=1867116#post1867116

    Reply
  4. https://upiter.novabb.ru/viewtopic.php?t=171

    Reply
  5. арендовать квартиру в Ташкенте долгосрочно Ташкент, современная столица Узбекистана, привлекает своим сочетанием истории и динамичного развития. Для тех, кто планирует остаться здесь на длительный срок, вопрос аренды жилья становится первостепенным. Снять квартиру в Ташкенте – задача, требующая внимательного подхода и понимания местного рынка.

    Reply
  6. http://printsstars.ru/communication/forum/index.php?PAGE_NAME=read&FID=1&TID=0&MID=479#message479

    Reply
  7. 1 vin [url=https://balashiha.myqip.ru/?1-12-0-00000437-000-0-0-1743258848]https://balashiha.myqip.ru/?1-12-0-00000437-000-0-0-1743258848[/url] .

    Reply
  8. GregoryRhisp

    Our promo code 1XBET 2025 helps to unlock an exclusive 1XBET welcome bonus for new players, and this guide will provide the information you need on how to maximize it. It includes an explanation of how to get and claim promo code 1XBET deals, presents the registration process and other top features like the 1XBET app. So let's start with what is the latest promo code for 1XBET?
    A boosted welcome bonus is offered at 1XBET for players using our code promo 1XBET 2025 while signing up. The bonus includes an extra 30% on the sports welcome bonus after the first deposit and a generous casino package with bonus cash and free spins with the first four deposits. In the following section, you can find the explanation how to use the 1XBET promo code and the presentation of 1XBET bonus offers and promotions for 2025 you can claim with our 1XBET promo code 2025.
    1xbet Promo Code – Free Bonus €/$130

    https://doctorthailand.net/articles/_promo_code____vip_welcome_bonus_130.html
    With the 1XBET bonus code 2025, you access exclusive bonuses for sports and casino. Grab an enhanced 130% sports betting bonus up to €130, and a casino package of up to €1950 + 150 free spins! The code has to be entered in the registration form.

    Reply
  9. Экономные счетчики Приборы учета с дистанционным управлением, электросчетчики, оснащенные пультом, устройства для измерения потребления электроэнергии с возможностью удаленного контроля, экономичные модели счетчиков, модифицированные приборы учета, разнообразные счетчики, газовые счетчики, подвергшиеся воздействию магнитом или пленкой, способы остановки работы счетчика, приобретение счетчика с пультом дистанционного управления, покупка электросчетчика с пультом.

    Reply
  10. Blaineroyal

    How to get 1xBet free promo code?
    Sign up on their website using the 1xBet promo code and receive an impressive 120% bonus on your initial deposit, up to a maximum of ?33,000. For instance, if you deposit ?1,000, you'll receive an additional ?1,200 in bonus funds, giving you a total of ?2,200 to kickstart your betting experience.
    What is voucher code in 1xBet?
    1xBet Promo Code Get 300% Bonus Up to GHS 3,445 in 2025. Sign-up with 1xBet using the promo code. New customers can get a 200%, 250% or 300% bonus. The 1xBet promo code. Use it on the sign-up page to get a 300% bonus up to 3445 GHS.
    1xbet Promo Code Offer Get 100% Bonus Up To $/€130
    1xbet promo
    Promo code for 1xBet, use this combination to increase your welcome bonus up to 100% on an amount reaching $/€130 for registration. These funds are available to all new players who have already created an account or are planning to do so. The bonus requires wagering, and it must be done in the sports section by placing bets with odds of at least 1.4 and a fivefold turnover. You have 30 days to use the code before it expires at the end of 2025.
    1xBet Promo Code 2025 - this is a huge bonus of up to $1950 for the casino and 150 free spins on slots. An exclusive offer for new players aged 18 and above. To activate the code, you need to make a deposit of $10. The second and subsequent deposits must be at least $15. You can participate in this promotion until the end of 2025.

    The 1xBet platform is one of the most popular in this domain. It has over a million fans worldwide and has earned players’ trust since 2007. Over time, the platform has evolved both in customer service and its interface.

    1xBet always puts its clients first, listening to feedback and suggestions to improve the platform. It was one of the first bookmakers to create a mobile application, gaining even more popularity among players.

    In today’s article, we will delve into the platform's promotions, particularly the welcome bonus that greets all new players after registration. We’ll explain how to use promo codes correctly to maximize their benefits.

    1xBet promo code today, by entering it during registration, you can increase the welcome bonus amount up to 100% and claim up to €130 on your gaming balance. The total amount of the awarded bonus will be available for wagering in the sports section for 30 days from the activation of the code. You need to place bets with odds of at least 1.4, a fivefold turnover, and a chain of no less than 3 events. Use the promo code in 2025 to get the maximum benefit from the welcome bonus.

    Reply