LeetCode Reverse Integer Solution Explained - Java

Поділитися
Вставка
  • Опубліковано 23 січ 2025

КОМЕНТАРІ • 93

  • @wayfarer2178
    @wayfarer2178 4 роки тому +156

    Integer.MAX_VALUE is equal 2147483647. Integer.MIN_VALUE is equal -2147483648. Last digits are 7 and 8. This is the reason why we check pop>7 and pop < -8 conditions

    • @edmund7476
      @edmund7476 3 роки тому +9

      Yes, that's his thought process behind it but after some thinking, I found that, you dont need those if statements (with && pop). It would not be possible to input an integer where reversed==Integer.MAX_VALUE/10 && pop >7.
      Ex: 8,463,847,412
      Ex: 7,463,847,412
      You can't input these numbers in the first place.

    • @edmund7476
      @edmund7476 3 роки тому +2

      @M His first if statement
      if(reversed>Integer.MAX_VALUE/10 || reversed 214,748,364(max/10)
      This will return 0.
      The most likely reason why he wrote an additional if statement case was just because it was the next logical thing to do. His thought process was probably, "ok we've taken care of reversed>max/10, now what about reversed==max/10". However it was a mistake because the case of (reversed==MAX/MIX_VALUE/10 && pop>7 / pop

    • @edmund7476
      @edmund7476 3 роки тому +1

      @M Glad I could contribute, and tbh, im not in a position to give tips. Im preparing too haha

    • @_abhishekmj_
      @_abhishekmj_ 3 роки тому

      @@edmund7476 So, you mean we cannot have original number of that size ( coz it is out of bound for integer) right? So, need not check.. Correct me if understanding wrong. But I think his soln helps if they improve question and say input is long :)

    • @edmund7476
      @edmund7476 3 роки тому +2

      @@_abhishekmj_ Yea, in that case the check would be needed but for this question, since it specifically says a 32 bit integer, there is no need.

  • @rayprusia4753
    @rayprusia4753 5 років тому +39

    Good Job, seeing your mistakes is good, makes us see how you debug

  • @pragyadhawan5818
    @pragyadhawan5818 4 роки тому +30

    Similar solution, easy to understand, checking the boundary condition before so we don't have to use pop
    int rev =0;
    while(x!=0)
    {
    if(revInteger.MAX_VALUE/10)
    return 0;
    rev = rev * 10 + x%10;
    x/=10;
    }
    return rev;

    • @akansha_vatsa
      @akansha_vatsa 4 роки тому +3

      why /10 ? please tell

    • @AvishekPaulOnline
      @AvishekPaulOnline 3 роки тому +2

      @@akansha_vatsa Next time rev would be multiplied by 10 that's why.

    • @extremeweirdness1528
      @extremeweirdness1528 3 роки тому

      I did the same thing got 1ms runtime although I think they fixed a bug or something

    • @rohamisamazing
      @rohamisamazing 3 роки тому +6

      You are actually incorrect, since you are only checking if the value is less than the (MIN_MIN/10) or higher than the (MAX_VALUE/10) but, not keeping track of the very last digit!
      For example think of this situation:
      Max_Value = 2147483647 --> (Max_Value/10) = 214748364
      Lets imagine:
      x =2147483649
      Your test would make this a pass since x < (Max_Value/10) however our x clearly a larger number than 2147483647 by two.
      That is why, an additional condition is needed to check in your if statement, if (rev == nteger.MIN) and x%10 is bigger than 7 or less than -8, which are the last digits of 2147483647 and -2147483648 for MAX and MIN values.

  • @ZhouHaibo
    @ZhouHaibo 4 роки тому +9

    Thanks for it, I convert it to Python format.
    ```
    class Solution:
    def reverse(self, x: int) -> int:
    reversed = 0
    sign = -1 if x < 0 else 1
    x = abs(x)
    while x > 0:
    pop = x % 10
    x //= 10
    reversed = reversed * 10 + pop
    if reversed > -2**31 and reversed < 2**31 - 1:
    return reversed * sign
    return 0
    ```

  • @ConwellConwell
    @ConwellConwell Рік тому +4

    Nick helped code 911 and grinder

  • @jollymail1
    @jollymail1 5 років тому +19

    why Pop > 7 or pop < -8 in boundary checking?

    • @shamsfaraj5367
      @shamsfaraj5367 5 років тому +37

      Max_value is 2147483647 and out equation is reversed = reversed*10+pop. If reversed == 214748364(2147483648/10) and pop == 8( greater than 7) then you'll exceeds the boundary and error will occur. The same thing is for min_value (-2147483648)

    • @itech40
      @itech40 5 років тому +1

      @@shamsfaraj5367 But can't we just put and if statement to verify the bounderies AFTER the whole process? So we don't have to care about that pop var. and we only do it once so it's not executed at every while iteration?

    • @channel-b
      @channel-b 4 роки тому +7

      ​@@itech40 Doing a bounds check after increasing the reversed variable wouldn't work in this example because at that point the 32-bit int would have already overflowed.
      Now I'm not saying it's a better solution but I believe in java a long is guaranteed to be 64-bit so it could contain the value of any reversed 32-bit int. Then making reversed a long you could get rid of the pop variable and just do:
      reversed = (reversed * 10) + x % 10;
      x /=10;
      in the loop and then check
      if (reversed > Integer.MAX_VALUE || reversed < Integer.MIN_VALUE) return 0;
      and finally return the typecasted value:
      return (int)reversed;

    • @jiyoungkim6888
      @jiyoungkim6888 4 роки тому

      @@channel-b Thank you for the explanation!

    • @channel-b
      @channel-b 4 роки тому

      @@jiyoungkim6888 You're welcome :)

  • @darod6098
    @darod6098 4 роки тому +12

    For those who do not understand the overflow check... it's not necessary :)
    We can do:
    int reversedCopy = reversed;
    reversed = reversed * 10 + pop;
    if ( (reversed - pop) / 10 != reversedCopy) {
    return 0
    }

  • @aislofi
    @aislofi 3 роки тому +3

    i didn't get it why there is reversed = (reversed * 10) + pop; ???

  • @CaseTechnologies
    @CaseTechnologies 3 роки тому +4

    Excellent job! You really broke this down for a novice like myself.

  • @matthewstraughn3539
    @matthewstraughn3539 4 роки тому +14

    Why does Integer.MAX_VALUE has to be divided by 10?

    • @amamdani15
      @amamdani15 4 роки тому +15

      Its because you are multiplying by reversed by 10 before you add pop to it. by dividing by 10, you are checking against what the value will be before you multiply and running into an overflow of the value of reversed.

  • @Fahodinho
    @Fahodinho 3 роки тому +1

    In 3:40 and 4:12 why do we have conditions for pop > 7 and pop

  • @jayhun
    @jayhun 4 роки тому +3

    I am having trouble understanding what reversed = (reversed * 10) + pop; does. What integer does reversed store? in other words, what is being multiplied by 10?

    • @notyournormaldev1419
      @notyournormaldev1419 4 роки тому

      It is actually creating a format of place of one's ten and hundreds multiply by ten shifts positions

    • @aislofi
      @aislofi 3 роки тому

      @@notyournormaldev1419 didn't get it, sorry

    • @DanielLeahy
      @DanielLeahy 11 місяців тому

      reversed is the reversed integer, it starts off as 0, he is using pop as temporary variable to store the remainder of division by 10, so for example 123 divided by 10 is 12 with a remainder of 3, that 3 will be the left most digit of the new integer, its a bit messy with his check for the limits of allowed integer to see did it go over the Max Integer value, you could do a reverse calculation, if ((temp - remainder) / 10 != result){
      return 0;
      }
      and compare with the pop/temp value previously calculated to see if no digits have been lost in the calculation
      @@aislofi

  • @yassergaber6428
    @yassergaber6428 4 роки тому +4

    Same approach but cleaner:
    public int reverse(int x) {
    long res = 0;
    for (; x != 0; x /= 10) res = (res * 10) + x % 10;
    if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0;
    return (int) res;
    }

    • @aipriyank
      @aipriyank 2 роки тому

      I tried this method and it's 100% faster than other submissions also the runtime is 1 ms.
      Thank you for the solution 👍

    • @gtx1650max-q
      @gtx1650max-q Рік тому

      Yeah, but that's the challenge that you shouldn't use long.

  • @lifeofamobiledeveloper3700
    @lifeofamobiledeveloper3700 4 роки тому +2

    Having watched a video where it was said when learning a new language it's good trying interview questions. So I did this question in Dart - and it's good to now refer to your video to see similar or differences in the way you approached.

  • @_-6912
    @_-6912 4 роки тому +3

    Hey Nick, why Min and Max values are divided by 10 and why do you check for pop being >7 or

    • @csninja1150
      @csninja1150 4 роки тому +4

      Min max is divided by 10 because you're checking for 2 things.
      1. Your number is within valid range
      2. You can multiply that number by 10 to add a number to it and still not go over the limit.
      The multiplication of 10 happens after you compare, so you need to take that into account and compare with a number divided by 10. Otherwise if you don't divide by 10 you'll run into errors.

  • @adityaranjalker6446
    @adityaranjalker6446 4 роки тому +3

    Help me understand the logic behind the pop>7 and pop < -8 conditions please.

    • @yxc4713
      @yxc4713 4 роки тому

      same question here!

    • @you123213
      @you123213 3 роки тому +6

      As you know after reversing number you need to check reversed number with in range (-2^31= -2147483648 to 2^31-1=2147483647) so that you either return 0 or reversed number. When Nick is checking for pop(basically remainder) < -8 or > 7 basically he is checking two things (reverse==int.MinValue/10 && remainder 7) which indicates number that are outside bounds of outside the signed 32-bit integer range [-2^31, 2^31 - 1].
      I added extra parentheses to make it clear:
      if( reverse >int.MaxValue/10 || (reverse==int.MaxValue/10 && remainder >7)) return 0;
      if( reverse

  • @TrollFreeInternet
    @TrollFreeInternet 5 років тому +12

    U didnt check for negative integers?

    • @csninja1150
      @csninja1150 4 роки тому

      When you use modulus that gets taken care of automatically. But modulus are sometimes different based on languages. So you can use this method in Java and C++ but it'll give you a wrong answer in Python. There, you'll have to check for the sign.

  • @thesoftwareengineer17
    @thesoftwareengineer17 4 роки тому +4

    Hey Nick,
    can u explain y we are using pop varibale inside the if conditions

    • @animeshkar4610
      @animeshkar4610 11 місяців тому

      Integer.MAX_VALUE is equal 2147483647. Integer.MIN_VALUE is equal -2147483648. Last digits are 7 and 8. This is the reason why we check pop>7 and pop < -8 conditions

  • @Gideon_Judges6
    @Gideon_Judges6 5 років тому +1

    Not sure how fancy their compiler is and if it optimizes, but if you take those MAX/MIN calculations out of the loop and store them in a variable then you are trading 4N divisions for just 2 total. A real compiler would probably optimize this though, and as you said there is a Wifi bug anyway. 😁

  • @rohansachdeva1able
    @rohansachdeva1able 4 роки тому +8

    Why divide the min and max's by 10?

    • @JoahW
      @JoahW 4 роки тому +9

      You are checking the boundary case before you do the operation. (reversed > Integer.MAX_VALUE) wouldn't work because reversed will overflow and become negative if it goes past MAX_VALUE. Dividing MAX_VALUE by 10 lets you check the condition without overflowing.

    • @anuragnagpal
      @anuragnagpal Рік тому

      @@JoahW Thank you this is really a good explanation

  • @abhinavmathur6072
    @abhinavmathur6072 4 роки тому +2

    Thank you buddy! Still watching

  • @guguls
    @guguls 3 роки тому +1

    what does line 14 do exactly?

  • @pratikawate5826
    @pratikawate5826 3 роки тому +3

    Can someone please elaborate why we divide Max and Min by 10..None of the comments helped me out plss 🙏

  • @r.varshitha7459
    @r.varshitha7459 7 місяців тому

    You don't need to check the condition reversed==Integer.MAX_VALUE/10 && pop>7 cause this would mean that the input should be 7463847412 ( reverse of 2147483647). This is outside the int range as in the question they mentioned the input is an integer. Similarly you also can avoid the reversed==Integer.MIN_VALUE/10 && pop

  • @masong5044
    @masong5044 4 роки тому +1

    why the while(x !=0) loop not a infinite loop?

  • @gabrielahernandez4236
    @gabrielahernandez4236 3 роки тому +1

    this was SO well-explained!!

  • @freelow3266
    @freelow3266 Рік тому

    this guy is just flexing his logic skills.

  • @giorgi23
    @giorgi23 4 роки тому +5

    First of all thanks for this. I think this these line below are redundant
    || reversed == Integer.MAX_VALUE / 10 && chunk > 7
    || reversed == Integer.MIN_VALUE / 10 && chunk < -8
    Just having this shown below should be enough
    if (reversed > Integer.MAX_VALUE / 10 || reversed < Integer.MIN_VALUE / 10) {
    return 0;
    }

    • @swantanbarua9327
      @swantanbarua9327 4 роки тому +1

      Why are we dividing by 10?

    • @CCV334
      @CCV334 4 роки тому +3

      @@swantanbarua9327 because it will overflow after you call rev = rev * 10 + pop;

    • @NarenRajVaka
      @NarenRajVaka 4 роки тому +5

      But then i think we are missing the case where reversed is actually equal to MAX or MIN VALUE

  • @helloitshecker
    @helloitshecker 2 роки тому

    While watching this video i figured out the solution myself. See this program -
    class rev
    { public int reverse(int num)
    { int quo, rem, ans=0;
    while ( num > 0)
    {
    quo = num/10;
    rem = num%10;
    ans = (ans*10)+rem;
    num = quo;
    } return(ans);
    }}

  • @xchen7499
    @xchen7499 3 роки тому

    Why do you divide by 10?

  • @memao87
    @memao87 Рік тому

    Does anyone know how to do this but with a string as an input?

  • @ericsodt
    @ericsodt 2 роки тому

    I'd love to see how mine compares:
    {code}
    int reverse(int i) {
    boolean isNegative = false;
    if(i < 0) {
    isNegative = true;
    i = Math.abs(i);
    }
    StringBuilder sb = new StringBuilder(String.valueOf(i));
    sb.reverse();
    String s = sb.toString();
    if(isNegative) {
    s = "-"+s;
    }
    return Integer.parseInt(s);
    }
    {code}

  • @kalyanreddy3176
    @kalyanreddy3176 3 роки тому +1

    I was not able to understand how this is working for negative integers.

    • @varungupta7226
      @varungupta7226 3 роки тому

      because : (123%10) = 3 and (-123%10) = -3

  • @okey1317
    @okey1317 3 роки тому

    Hi, can someone explain what is meant by 32 bit signed integer?

    • @andregoulbourne839
      @andregoulbourne839 3 роки тому

      32 bit just refers to the size of the memory allocated to integer.

  • @bookquick7017
    @bookquick7017 4 роки тому

    Why is negative input not taken care of?
    123%10 = 3 but -123%10=7

    • @_abhishekmj_
      @_abhishekmj_ 3 роки тому +1

      In java -123%10 = -3 . Java modulus returns negative for negative number..

  • @vinodphalke2121
    @vinodphalke2121 Рік тому

    Please bro ensure that before upload videos on youtube .. your voice intensity is too low.. please loud as much as possible .. your videos are outstanding

  • @balamuruganradhakrishnan7540
    @balamuruganradhakrishnan7540 2 роки тому

    Can any one please help understand why this will not work ?
    public int reverse(int x) {
    int pop=0;
    int reversed=0;
    while(x != 0){
    pop=x % 10;
    x /= 10;
    reversed=(reversed * 10) + pop;
    if(reversed > Integer.MAX_VALUE / 10 || (reversed==Integer.MAX_VALUE/ 10 && reversed % 10 > 7)){
    return 0;
    }
    if(reversed < Integer.MIN_VALUE / 10 || (reversed==Integer.MIN_VALUE/ 10 && reversed % 10 < -8)){
    return 0;
    }
    }
    return reversed;
    }
    Only change in above code when compared to above solution is , the check for overflow is being performed once after reversed is assigned the value. Instead of checking in next loop, why its a problem if its being checked immediately ? appreciate help to understand

    • @atib1980
      @atib1980 2 роки тому

      The problem with writing the if conditions later is that after doing the 10th iteration in the while loop while calculating the reversed number for an input number, lets say 1234567899, reversed = 998765432 * 10 + 1 will overflow the maximum valid value an int can hold (Integer.MAX_VALUE), 998765432 * 10 + 1 = 9987654321 is greater than 2147483647 and cannot be stored in a variable of type int on the JVM. It can only be stored in variable of type long (64-bit singed integral type on the JVM).

  • @زانغت_ساما
    @زانغت_ساما 4 роки тому

    thanks !!!! i learned alot

  • @BLUc18
    @BLUc18 3 роки тому

    int lastDig;
    int firstPart = 0;
    long res = 0;
    while (x!=0) {
    lastDig = ( x % 10 );
    res = res*10 + lastDig;
    x/=10;
    }
    if (res != (int)res) {
    return 0;
    }

    return (int)res;

  • @MaminaZvezdochka
    @MaminaZvezdochka 3 роки тому

    So lovely ❤️ thanks

  • @architjamaiyar5095
    @architjamaiyar5095 3 роки тому

    No body does it

  • @zaiterzaiter2034
    @zaiterzaiter2034 Рік тому

    Very slow

  • @gracioussaxena8318
    @gracioussaxena8318 5 років тому +1

    I got 1ms time

  • @DilmurodRozikov-xq5xo
    @DilmurodRozikov-xq5xo 2 роки тому +1

    check this out
    long reversed = 0;
    while(x != 0){
    int a = x % 10;
    x /= 10;
    reversed = reversed * 10 + a;
    }
    if(reversed > 2147483647 || reversed < -2147483648){
    return 0;
    }
    return (int)reversed;
    }