Reverse an Integer value - LeetCode Interview Coding Challenge [Java Brains]

แชร์
ฝัง
  • เผยแพร่เมื่อ 25 ส.ค. 2019
  • Interview Question: Reverse an integer in Java
    Leetcode link: leetcode.com/problems/reverse...
    Solution Gist: gist.github.com/koushikkothag...
    Difficulty level: Easy
    Language: Java
    Welcome to the Java Brains Java Interview challenge series of videos where we tackle various coding challenges ranging from the beginner level to advanced level - especially in the context of coding interviews.
    Any coding problems you would like me to explore? Please let me know in the comments what you think!
    #java #interview #javabrains

ความคิดเห็น • 108

  • @DK-sc5vn
    @DK-sc5vn 3 ปีที่แล้ว +8

    I did the same but my code was way longer. Your solution is the best. Just add "
    return reversed;"
    after while loop ends

  • @fufuisgood
    @fufuisgood 3 ปีที่แล้ว +2

    Wow this is the first video I have seen from your channel and it is amazing! You go in deepth and make it so understandable, and then later implement the code! love it!!!!

  • @dkryeziu
    @dkryeziu 4 ปีที่แล้ว +1

    That was awesome!!!
    Thank you very much Koushik, today I learned something new, really appreciate!

  • @nabilelhaouari1004
    @nabilelhaouari1004 4 ปีที่แล้ว +26

    I got this challenge in an interview, I have just converted the integer to string, I reverse the string and convert back to a number :)

    • @devsuper5972
      @devsuper5972 4 ปีที่แล้ว +3

      thats kinda like cheating 😊 ... never convert one data structure to another

    • @Your-Average-Gym-Bro
      @Your-Average-Gym-Bro 4 ปีที่แล้ว +2

      Dev Super I am just curious why it is cheating ? And why it is a bad sign during an interview? Could you elaborate a bit more detail please ?

    • @hermesmercuriustrismegistu4841
      @hermesmercuriustrismegistu4841 4 ปีที่แล้ว +8

      Happydoodle Pa it is totally ok. In development casting and converting data structures is normal but doing mathematical calculations might impress the interviewer since all people would think of transforming the integer to string but few would think of using modulo and division

    • @ahmeddaou8369
      @ahmeddaou8369 3 ปีที่แล้ว +4

      did you get the job?

    • @TacklessNebula3
      @TacklessNebula3 3 ปีที่แล้ว +1

      ​@@Your-Average-Gym-Bro I wonder the same... Cuz as I was practicing the same problem, I thought of using the same approach!
      .
      .
      .
      .
      I still do!!!

  • @sirjonaz
    @sirjonaz 3 ปีที่แล้ว +4

    "exceptions are for exceptional situations" - I'm stealing that line. :)

  • @RameenFallschirmjager
    @RameenFallschirmjager 4 ปีที่แล้ว +21

    very enjoyable video. Having moments like this reminds me that intellectual satisfaction is highest form of pleasure. thank you sir.

  • @thanga2317
    @thanga2317 4 ปีที่แล้ว +2

    We appreciate you ..!!! keep solving more leetcode problems..

  • @diegoguzman4631
    @diegoguzman4631 2 ปีที่แล้ว

    These videos are easy to follow and understand. Thanks, Koushik!

  • @parshuramrv848
    @parshuramrv848 4 ปีที่แล้ว +1

    Thank u very much sir for leetcode keep solving more problems

  • @sagarmeena0210
    @sagarmeena0210 4 ปีที่แล้ว +2

    great tutorial....pls more of problem coding for interviews

  • @ivanviveros
    @ivanviveros ปีที่แล้ว

    Your videos have been so helpful and clear! You rock

  • @katiesun1533
    @katiesun1533 4 ปีที่แล้ว

    Excellent as always 👍

  • @prashantsurti5788
    @prashantsurti5788 3 ปีที่แล้ว +1

    Subscribed ... very enjoyable

  • @niteshrajput308
    @niteshrajput308 3 ปีที่แล้ว

    Thanks sir , i really got help for your video.

  • @steveotieno8441
    @steveotieno8441 2 ปีที่แล้ว

    wonderful explanation

  • @ShinAkuma
    @ShinAkuma 3 ปีที่แล้ว +2

    int a = 54321;
    StringBuffer str = new StringBuffer( ""+a );
    System.out.println( str.reverse().toString() );
    In this solution, Need to check if it's +ve or -ve and add the sign later on accordingly.
    This is shorter but requires parsing int to string which is less efficient, but it does the job for lazy people like me. I'm sure the client won't mind waiting 1 extra second for his reversed number.

  • @hayatbasha404
    @hayatbasha404 3 ปีที่แล้ว

    Thank u so much Sir!!

  • @arularook6374
    @arularook6374 4 ปีที่แล้ว

    Sirrrr❤😍...

  • @meeradad
    @meeradad 10 วันที่ผ่านมา

    I think the sign of the integer being reversed needs to be handled outside the reversal. So one has to take the absolute value of the number, reverse that absolute value, and then multiply the reversed number with 1 or -1 depending on the sign of the original number. At least in Python, the remainders of -ve numbers do not work in a sign-agnostic way.

  • @abhijitmadchetti5443
    @abhijitmadchetti5443 3 ปีที่แล้ว

    I think while condition should be replaced with while (input > 9) and after while loop 1 more statement reversed = reversed * 10 + input; for last digit. It will work for input < 10.

  • @msk9414
    @msk9414 2 ปีที่แล้ว

    This problem is also a good candidate for recursion as we are decreasing the input at every iteration
    private static long reverse(int input) {
    if (input

  • @Aaron-yu6zo
    @Aaron-yu6zo 3 ปีที่แล้ว +3

    I wonder if I can use an array to inverse this array.

  • @saddamahmad2310
    @saddamahmad2310 4 ปีที่แล้ว

    thank you very much sir for this video

  • @HammamMounir
    @HammamMounir 4 ปีที่แล้ว +6

    What about this proposition :
    public Integer reverse(Integer myInt){
    String s = ""+myInt;
    String s2 = "";
    for(int i=0;i

  • @sharathchandrareddy8959
    @sharathchandrareddy8959 4 ปีที่แล้ว +1

    Two things to mention here
    1. The code did handle the exception cases of integer range boundaries BUT didn't return the "reversed" value outside the loop to handle the happy case
    2. I understand that A smaller number in the range of integer might possible cross the integer range while reversing ( Reverse of 12345 is 54321 ) which is bigger than original . Is the min range meant to handle the negative integer numbers ?

  • @jackthestripper6388
    @jackthestripper6388 4 ปีที่แล้ว +2

    I solved it with a long variable and it passed all cases in leetcode. Is it an incorrect or novice approach?

  • @whiterose5083
    @whiterose5083 4 ปีที่แล้ว

    I have much towards you brah..

  • @antonslonkin
    @antonslonkin 3 ปีที่แล้ว +1

    Mayby it will be simplier?
    StringBuilder reversedNumber = new StringBuilder(Integer.toString(number));
    return Integer.parseInt(reversedNumber.reverse().toString());

  • @rushikeshr21280
    @rushikeshr21280 6 หลายเดือนก่อน

    I think, this could also be achieved by reversing string. String str="54321";
    int reveserInt=Integer.parseInt(new StringBuilder(str).reverse().toString());

  • @burramahesh
    @burramahesh 4 ปีที่แล้ว +2

    Spring security please

  • @talhashan6355
    @talhashan6355 3 ปีที่แล้ว +1

    great ! very similar to Armstrong number problem

  • @navanshu-007
    @navanshu-007 4 ปีที่แล้ว +33

    take care of your health kaushik . You don't look Ok to me . Health is very important especially for guys like us who keep sitting for long hours

    • @devsuper5972
      @devsuper5972 4 ปีที่แล้ว +3

      dont judge a book by its cover

  • @suj241
    @suj241 4 ปีที่แล้ว +3

    err: lossy conversion from long to int.. did you ëven try it on Leecode or just ran it on your computer and lived happily ever after?

    • @prag3022
      @prag3022 4 ปีที่แล้ว

      dude use (int)reversed.

    • @pradeepjaiswal9706
      @pradeepjaiswal9706 3 ปีที่แล้ว

      @@prag3022 what about negative nos ?

  • @ConstantinKubrakov
    @ConstantinKubrakov 4 ปีที่แล้ว

    Why do you reverse decimal digits not bits?

  • @dhamu2win
    @dhamu2win 2 ปีที่แล้ว

    Thanks for helping the developer community. Keep it up. I think there is a small correction in your code but its not a trivial ...if(reversed > Long.MAX_VALUE || reversed < Long.MIN_VALUE) {....

    • @bbvkishore
      @bbvkishore 2 ปีที่แล้ว +1

      May be not. We need to be able to convert long reversed into integer right.. But I feel the last return statement is missing..
      Since it is just a psudo code.. interviewer will be okay I guess..

    • @dareSh0
      @dareSh0 2 ปีที่แล้ว

      @@bbvkishore something like this is needed at the end:
      return (int)reversed;

  • @stephyjacob1256
    @stephyjacob1256 4 ปีที่แล้ว +7

    What happened to spring security topics? I was waiting for next video... Please continue on spring security also.

    • @Java.Brains
      @Java.Brains  4 ปีที่แล้ว +13

      Yes, working on the next Spring Security video right now!

    • @stephyjacob1256
      @stephyjacob1256 4 ปีที่แล้ว

      @@Java.Brains Thanks Man

    • @sarathkumarm9734
      @sarathkumarm9734 4 ปีที่แล้ว

      @@Java.Brains nice video

  • @cjimenez2581
    @cjimenez2581 11 หลายเดือนก่อน

    what would be the problem of returning BigInteger? and we dont check if we pass the min/max value

  • @tsbr007
    @tsbr007 3 ปีที่แล้ว

    For String
    public static void main(String[] args) {
    String a = "aba";


    String reverse = "";

    for (int i = a.length() - 1 ; i >= 0 ; i--)
    reverse = reverse + a.charAt(i);

    System.out.println(reverse);


    }

  • @MegaDk13
    @MegaDk13 4 ปีที่แล้ว +1

    With a 32 bit signed unsigned integer long cannot be used which is a 64 bit data type

    • @csninja1150
      @csninja1150 3 ปีที่แล้ว

      It can be used if you cast it to an int while returning. Otherwise you can just start off with an int in the first place, but this requires a bit of recoding inside the while loop.

  • @fadlimohamed3778
    @fadlimohamed3778 3 หลายเดือนก่อน

    hello ! i converted the int into a string using the string class and then i reversed it by charAt() method. my question is this way correct ?

  • @arpit39agarwal
    @arpit39agarwal 4 ปีที่แล้ว +1

    what about negative numbers

  • @NehaSingh-xg7ri
    @NehaSingh-xg7ri 2 ปีที่แล้ว

    why are we not returning the int value of the reversed number? The method expects an int return type.

  • @rahul-vz6zd
    @rahul-vz6zd 4 ปีที่แล้ว

    i didn't understand the code at the line -- input/=10; shouldn't it be input = input/10; ?

  • @ugorjichukwudi5527
    @ugorjichukwudi5527 4 ปีที่แล้ว +1

    Sir, I was thinking, would it be wrong if one just convert the integer to string and reverse the string using string builder

    • @Java.Brains
      @Java.Brains  4 ปีที่แล้ว +6

      It would be very inefficient. You can mention that in the interview, but the interviewer will likely not accept that as the final solution

    • @ugorjichukwudi5527
      @ugorjichukwudi5527 4 ปีที่แล้ว

      @@Java.Brains ok, thanks for pointing out the inefficiency. I was actually thinking about that

  • @ckal123
    @ckal123 2 ปีที่แล้ว

    Can anyone explain me why the reversed is multiplied by 10? Let's say we found the last digit by using modulus (%) of 10 then why do we have to multiply it by 10 again???

  • @gauravsrivastava17
    @gauravsrivastava17 4 ปีที่แล้ว

    Will this code run for n=100 or any zero digit number?
    Because 0*10 is zero got nothing

    • @laurentiuionele6366
      @laurentiuionele6366 3 ปีที่แล้ว

      Yes, it will work. It will return 1, which is the expected answer. If you thought that is should return 001 then that is not the case, as that is not a valid integer.

  • @shirshakroy5979
    @shirshakroy5979 3 ปีที่แล้ว

    Can someone explain once again what happened in reverse *10 line

  • @SuperYouthful
    @SuperYouthful 3 ปีที่แล้ว

    Integer revNum = new Integer (num); String RevString = RevNum.toString ();
    String temp = "";
    For (int I = RevString.length() -1, I--, I

  • @shubhamkhare4217
    @shubhamkhare4217 3 ปีที่แล้ว

    Is it ok if I convert int to stringBuilder by String.valueOf and then reverse that string n convert it back to Integer by Integer.getValue?

    • @erickjhormanromero6905
      @erickjhormanromero6905 3 ปีที่แล้ว

      i will surely work but your will make lotta operations which increment the O(longN) of the algorithms so i think you can find a better solution
      i have this one from anothe guy and already understood this concept
      public static int reverseInteger() {
      int x = 54321;
      int result = 0;
      int prev = 0;
      while (x != 0) {
      System.out.println("x" + x);
      int cur = x % 10;
      System.out.println("cur" + cur);
      x /= 10;
      System.out.println("cur / " + x);
      result = result * 10 + cur;
      System.out.println("result" + cur);
      if ((result - cur) / 10 != prev) return 0;
      prev = result;
      }
      return result;
      }
      it works like a charm

  • @prernasemwal3016
    @prernasemwal3016 3 ปีที่แล้ว

    why aren't we checking for negative values?

  • @mrwalkan
    @mrwalkan 3 ปีที่แล้ว

    public static int revInteger(int quotent) {
    int reverse = 0;
    while (true) {
    if(quotent == 0) break;
    reverse = reverse * 10 + quotent % 10;
    quotent /= 10;
    }
    return reverse;
    }

  • @cosepeter2197
    @cosepeter2197 2 ปีที่แล้ว

    What happens if input is 0?

  • @nishanksoni2037
    @nishanksoni2037 2 ปีที่แล้ว

    You shouldn't use long type. It is clearly mentioned that the input is a 32 bit signed integer value. It's just a hack you are applying

  • @swarupkumar2
    @swarupkumar2 4 ปีที่แล้ว

    Why the if-statement is inside the while-loop?

    • @csninja1150
      @csninja1150 3 ปีที่แล้ว

      Because you're checking for the limit as you're adding numbers into the reversed variable

  • @BetoRomeroG
    @BetoRomeroG ปีที่แล้ว

    It does not work for number 10. The result should be 01 but instead it is giving 1

  • @ankitarani6784
    @ankitarani6784 3 ปีที่แล้ว

    It is showing error

  • @sivaprakashrajarathinam2063
    @sivaprakashrajarathinam2063 4 ปีที่แล้ว

    if(reversed > Integer.MAX_VALUE || reversed < Integer.MIN_VALUE)
    Since Integer roll over happens, this did not work. The following code works fine for me.
    public int reverseInt(int value) {
    int input = value;
    int reversed = 0;
    while(input != 0) {
    reversed = reversed * 10 + input % 10;
    input = input / 10;
    if((reversed < 0 && value > 0) || (reversed > 0 && value < 0) ) {
    // throw error or return 0
    return 0;
    }
    }
    return reversed;
    }

  • @RameenFallschirmjager
    @RameenFallschirmjager 4 ปีที่แล้ว

    I didn't understand the integer.max or integer.min part.

    • @authoritycamper
      @authoritycamper 4 ปีที่แล้ว +3

      Let's say our input is a very large number: 2147483647 If we reverse this we get: 7463847412 Guess what will be the problem here? Do you see it? The reverse number far exceeds the Integer.MAX_VALUE. And then the internet will come crashing down, just kidding of course. Hope you see it.

    • @RameenFallschirmjager
      @RameenFallschirmjager 4 ปีที่แล้ว +1

      @@authoritycamper thanks dude! great explanation. god bless Indian people!

    • @baibhavghimire6576
      @baibhavghimire6576 4 ปีที่แล้ว

      @@authoritycamper class Solution {
      public int reverse(int x) {
      long sum=0;
      int temp=x;
      int r;
      while(x!=0){
      r=x%10;
      sum=(sum*10)+r;
      x=x/10;
      }
      if(sum>Integer.MAX_VALUE || sum

  • @devpkn
    @devpkn 4 ปีที่แล้ว

    054321 which is not reversed . Giving result 73722

  • @smoothoperator8414
    @smoothoperator8414 3 ปีที่แล้ว

    Nug

  • @praveenj3112
    @praveenj3112 4 ปีที่แล้ว

    Simple logic it works:
    StringBuilder sb=new StringBuilder();
    while (n>=10) {
    int last=n%10;
    sb.append(last);
    n/=10;
    }
    System.out.println(sb.toString());

  • @praveenj3112
    @praveenj3112 4 ปีที่แล้ว

    The below solution which gives o(n) time complexity :
    StringBuilder sb=new StringBuilder();
    while (n>=10) {
    int last=n%10;
    sb.append(last);
    n/=10;
    }
    if(sb!=null){
    sb.append(n);
    }
    System.out.println(sb.toString());
    }

    • @thomasandolf7365
      @thomasandolf7365 4 ปีที่แล้ว +2

      this will not handle negative numbers, -123 will become -123 and this is way more memory intensive than the proposed answer. Usually you trade memory for speed or speed for memory. This doesn't trade at all, it increases memory but gains no speed.

  • @SushilKumarBhaskar
    @SushilKumarBhaskar 4 ปีที่แล้ว

    leetcode Message :
    1032 / 1032 test cases passed.
    Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse Integer.
    Memory Usage: 33.7 MB, less than 11.66% of Java online submissions for Reverse Integer.
    class Solution {
    public int reverse(int input) {
    long result=0;
    boolean flag=false;
    if(input0) {
    result=input%10+result*10;
    input=input/10;
    if(result> Integer.MAX_VALUE || result

  • @eakerz5642
    @eakerz5642 4 ปีที่แล้ว

    StringBuilder sb = new StringBuilder(String.valueOf(number)).reverse();
    System.out.println(sb.toString());

    • @thomasandolf7365
      @thomasandolf7365 4 ปีที่แล้ว +7

      this will not work with negative numbers, "-123" will become "321-" and also this is extremely much slower and more memory intensive than the proposed solution in the video. If you would answer that in an interview, you'd probably not get the job, and also this does not return an integer, but a stringbuilder.
      an integer in java takes up 4 bytes of memory while a String in java takes up at least "the number of chars" * 2 + 32 + rounded off to the nearest number devisable by 8.
      So the integer 123 takes up 4 bytes. The string 123 takes up 3 * 2 + 32 = 38 and then we round it off to the nearest number that can be divided by 8, and that is 40... so that string will take up at least 40 bytes.
      That is 10 times as much memory.

    • @vignesh4352
      @vignesh4352 4 ปีที่แล้ว +1

      @@thomasandolf7365 very clear explanation for how to evaluate the memory allocation. Thanks.

    • @eakerz5642
      @eakerz5642 4 ปีที่แล้ว +1

      Indeed, it's inefficient and slower. Thanks for the explanation!

    • @anandnanda3953
      @anandnanda3953 4 ปีที่แล้ว

      When ever interviewer ask without reverse () then it would happen

    • @raveendrau
      @raveendrau 4 ปีที่แล้ว

      @@thomasandolf7365, Yes you're right, but in realtime scenarios I have never seen a need revetse integer in my 4-5 of coding job. Why would people will as such kind of questions in interview?

  • @mrmagician5609
    @mrmagician5609 4 ปีที่แล้ว

    Your code doesn't handle cases as:
    100 => 001 which is wrong. Instead, it should be 1
    So, please handle such cases too!

    • @siennaalyssa6225
      @siennaalyssa6225 4 ปีที่แล้ว +3

      The return input is a 'long' number, when 0*10 it's 0 not 00 so it is 1 not 001

  • @hermesmercuriustrismegistu4841
    @hermesmercuriustrismegistu4841 4 ปีที่แล้ว

    Not reminder it is remainder I guess before being a software engineer you have to learn English well

  • @cvxcfv
    @cvxcfv 2 ปีที่แล้ว

    SKIP this video if you're trying to learn the solution quick. Too much unnecessary jargon

  • @ashleyrodrigues1468
    @ashleyrodrigues1468 4 ปีที่แล้ว +1

    Hey... Slow down a bit... useless explaination

    • @asashish905
      @asashish905 4 ปีที่แล้ว +4

      Hey! go to settings and reduce video pace... Useless!

  • @suneeljanu
    @suneeljanu 3 ปีที่แล้ว +1

    the logic which you gave would fail, when we have this input value 1534236469 which would not return 0