Tuesday, December 10, 2019

How To Opposite Integer Inward Coffee - Leetcode Solution

LeetCode has a occupation to opposite digits of an integer let out without using whatsoever library method similar reverse() method of StringBuffer. In LeetCode, yous tin displace solve this occupation amongst many unlike languages e.g. Java, C, C++, C#, Python, Ruby as well as fifty-fifty JavaScript. BTW, inwards the article, nosotros volition larn how to solve this occupation inwards Java. Before approaching solution let's kickoff read the occupation disceptation :

Reverse digits of an integer.

Example 1: x = 123, provide 321
Example 2: x = -123, provide -321

The occupation looks unproblematic but it's non unproblematic at that topographic point are many things yous request to consider inwards fellowship to create a solution which is accepted past times LeetCode, which has thousands of assay out cases to assay out your solution.


For example, yous request to consider non precisely virtually positive integer but equally good virtually negative integer. Remember, a positive integer tin displace equally good live written using + sign, thence yous request to grip that equally well. If the integer's concluding digit is 0, what should the output be? i.e. cases such equally 10, 100.

If the provide type of method is an integer as well as thence yous tin displace precisely provide 1, it's perfectly Ok, but if the provide type of method is String as well as thence yous may request to provide 001 or 0001. For the role of this solution, nosotros facial expression our method to provide an integer, thence 1 is fine.




Java Solution : Reverse Integer without library method

Here is my Java programme to solve this occupation of reversing integer let out without using whatsoever straight library method. The crux of this occupation is how to utilization sectionalization as well as modulo operator inwards Java to acquire the concluding digit of a let out as well as acquire rid of the concluding digit equally well.

If yous remember, I cause got shared this describe a fast 1 on earlier when I was explaining how to utilization modulo operator inwards Java. This is a actually non bad describe a fast 1 on as well as volition assistance yous to solve many programming problems where yous request to split numbers into private digits. When yous split a let out past times 10, yous acquire rid of the concluding digit, for example, 211/10 volition give yous 21, as well as 21/10 volition give yous 2, thence yous got rid of concluding 2 digits past times dividing your let out past times 10 twice.

Similarly, yous tin displace utilization let out modulo 10 to acquire the concluding digit of the number, for example, 221%10 volition provide 1, which is the concluding digit as well as 22%10 volition provide 2, which is the concluding digit of 22. You tin displace apply this logic until yous processed the concluding digit. Now the query comes, how attain yous adapt those digits inwards opposite order? Well, yous tin displace utilization precisely opposite i.e. multiplication as well as add-on to creating a novel let out amongst digits of the onetime let out inwards opposite order.  I cause got used next logic to gather digits into opposite fellowship :

reverse = opposite * 10 + lastDigit;

You tin displace run into past times multiplying let out past times 10 yous growth let out of digits past times 1 as well as and thence add together concluding digit. For negative numbers, nosotros multiply it past times -1 to kickoff arrive positive as well as and thence apply same logic, piece returning let out nosotros precisely multiply it past times -1 over again to convert the reversed let out into negative.

import java.util.Scanner;  /**  * Java Program to opposite Integer inwards Java, let out tin displace live negative.  * Example 1:  x = 123, provide 321  * Example 2:  x = -123, provide -321  *  * @author Javin Paul  */  public class ReverseInteger{      public static void main(String args[]) {         int input = 5678;         int output = reverseInteger(5678);         System.out.println("Input : " + input + " Output : " + output);     }      /*      * Java method to opposite an integer value. at that topographic point are duet of corner cases      * which this method doesn't grip e.g. integer overflow.      */     public static int reverseInteger(int number) {         boolean isNegative = let out < 0 ? true : false;         if(isNegative){             let out = let out * -1;         }         int opposite = 0;         int lastDigit = 0;          while (number >= 1) {             lastDigit = let out % 10; // gives yous concluding digit             opposite = opposite * 10 + lastDigit;             let out = let out / 10; // acquire rid of concluding digit         }          return isNegative == true? reverse*-1 : reverse;     }  }  Result : Input : 5678 Output : 8765

You tin displace run into that output is the precisely opposite of input. The kickoff digit has exchanged seat amongst concluding digit, minute amongst minute concluding as well as thence on.

By the way, if yous are solving LeetCode problems equally component of your interview grooming as well as thence yous tin displace equally good see Programming Interviews Exposed and Cracking the Coding Interview, 2 of the most useful books for preparing programming chore interviews. You volition larn to a greater extent than inwards a curt time.



JUnit Tests for Solution of Reverse Integer inwards Java

Here is my express laid of JUnit tests for checking my solution. It checks for input nada as well as one, a unproblematic positive number, a negative number, a positive let out amongst summation sign as well as let out ending amongst zero. Our solution passes all the tests but it's non enough. If yous submit this solution on LeetCode it exclusively managed to exceed 1028 out of 1032 assay out cases. Yes, yous read it write, they cause got 1032 to assay out this problem, no wonder our solution failed. FYI, it failed for input 1534236469, run into if yous tin displace spot the põrnikas as well as create it.

import org.junit.*; import static org.junit.Assert.*; /**  * JUnit assay out iv our solution to occupation of opposite Integer inwards Java.  *  * @author WINDOWS 8  *  */ public class ReverseIntegerTest{      @Test     public void testZeroAndOne(){         assertEquals(0, ReverseIntegerTest.reverseInteger(0));         assertEquals(1, ReverseIntegerTest.reverseInteger(1));           }         @Test     public void testSimple(){         assertEquals(4321, ReverseIntegerTest.reverseInteger(1234));         }         @Test     public void testNegative(){         assertEquals(-321, ReverseIntegerTest.reverseInteger(-123));           }         @Test     public void testNumberWithSign(){         assertEquals(321, ReverseIntegerTest.reverseInteger(+123));     }         @Test     public void testNumberEndingWithZero(){         assertEquals(1, ReverseIntegerTest.reverseInteger(1000));         assertEquals(1, ReverseIntegerTest.reverseInteger(10));           }     } 

as well as hither is the trial of running these JUnit assay out illustration inwards Eclipse :

 LeetCode has a occupation to opposite digits of an integer let out without using whatsoever library m How to opposite Integer inwards Java - LeetCode Solution

You tin displace run into that lovely greenish bar, which way all 5 tests are passed.

That's all virtually how to opposite Integer inwards Java. By the way, this solution is prone to integer overflow as well as volition non live expected at Leetcode.  It exclusively managed to exceed 1028 assay out cases out of staggering 1032 tests as well as failed for input 1534236469. Expected solution, inwards that case, is nada but our programme impress something else, run into if yous tin displace spot the põrnikas as well as create it.

Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures as well as Algorithms: Deep Dive Using Java
solution)
  • How to swap 2 integers without using a temporary variable? (solution)
  • How to impress Fibonacci serial inwards Java without using Recursion? [solution]
  • How to banking concern fit if an integer is a ability of 2 without using sectionalization or modulo operator?[hint]
  • How to banking concern fit if a String is Palindrome inwards Java? [solution]
  • How to honor the missing let out inwards a sorted array inwards Java? [answer]
  • How to honor all permutation of String inwards Java? [solution]
  • How to remove element from array without using tertiary political party library (check here)
  • How to honor largest as well as smallest let out inwards an array inwards Java (read here)
  • How to honor 2 maximum let out on integer array inwards Java (check here)

  • Hint : Leetcode is OK if your role returns 0 when the reversed integer overflows. Since our code doesn't grip integer overflow similar this, I left this equally an practice for yous guys to fix.

    No comments:

    Post a Comment