How to contrary Integer inwards Java - LeetCode Solution

LeetCode has a occupation to opposite digits of an integer publish without using whatever library method similar reverse() method of StringBuffer. In LeetCode, yous tin give notice solve this occupation amongst many unlike languages e.g. Java, C, C++, C#, Python, Ruby together with fifty-fifty JavaScript. BTW, inwards the article, nosotros volition larn how to solve this occupation inwards Java. Before approaching solution let's offset read the occupation tilt :

Reverse digits of an integer.

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

The occupation looks uncomplicated but it's non uncomplicated at that topographic point are many things yous demand to consider inwards club to create a solution which is accepted past times LeetCode, which has thousands of attempt cases to attempt your solution.


For example, yous demand to consider non exactly nigh positive integer but too nigh negative integer. Remember, a positive integer tin give notice too live written using + sign, hence yous demand to handgrip that equally well. If the integer's final digit is 0, what should the output be? i.e. cases such equally 10, 100.

If the provide type of method is an integer hence yous tin give notice exactly provide 1, it's perfectly Ok, but if the provide type of method is String hence yous may demand to provide 001 or 0001. For the role of this solution, nosotros await our method to provide an integer, hence 1 is fine.





Java Solution : Reverse Integer without library method

Here is my Java programme to solve this occupation of reversing integer publish without using whatever straight library method. The crux of this occupation is how to usage sectionalization together with modulo operator inwards Java to acquire the final digit of a publish together with acquire rid of the final digit equally well.

If yous remember, I guide maintain shared this fob earlier when I was explaining how to usage modulo operator inwards Java. This is a actually cracking fob together with volition aid yous to solve many programming problems where yous demand to split numbers into private digits. When yous split a publish past times 10, yous acquire rid of the final digit, for example, 211/10 volition give yous 21, together with 21/10 volition give yous 2, hence yous got rid of final 2 digits past times dividing your publish past times 10 twice.

Similarly, yous tin give notice usage publish modulo 10 to acquire the final digit of the number, for example, 221%10 volition provide 1, which is the final digit together with 22%10 volition provide 2, which is the final digit of 22. You tin give notice apply this logic until yous processed the final digit. Now the enquiry comes, how attain yous adapt those digits inwards opposite order? Well, yous tin give notice usage exactly opposite i.e. multiplication together with add-on to creating a novel publish amongst digits of the erstwhile publish inwards opposite order.  I guide maintain used next logic to get together digits into opposite club :

reverse = opposite * 10 + lastDigit;

You tin give notice encounter past times multiplying publish past times 10 yous growth publish of digits past times 1 together with hence add together final digit. For negative numbers, nosotros multiply it past times -1 to offset acquire inwards positive together with hence apply same logic, field returning publish nosotros exactly multiply it past times -1 i time again to convert the reversed publish into negative.

import java.util.Scanner;  /**  * Java Program to opposite Integer inwards Java, publish tin give notice 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 yoke of corner cases      * which this method doesn't handgrip e.g. integer overflow.      */     public static int reverseInteger(int number) {         boolean isNegative = publish < 0 ? true : false;         if(isNegative){             publish = publish * -1;         }         int opposite = 0;         int lastDigit = 0;          while (number >= 1) {             lastDigit = publish % 10; // gives yous final digit             opposite = opposite * 10 + lastDigit;             publish = publish / 10; // acquire rid of final digit         }          return isNegative == true? reverse*-1 : reverse;     }  }  Result : Input : 5678 Output : 8765

You tin give notice encounter that output is the exactly opposite of input. The offset digit has exchanged seat amongst final digit, minute amongst minute final together with hence on.

By the way, if yous are solving LeetCode problems equally portion of your interview grooming hence yous tin give notice too 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 brusk 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 nix together with one, a uncomplicated positive number, a negative number, a positive publish amongst summation sign together with publish 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 operate past times 1028 out of 1032 attempt cases. Yes, yous read it write, they guide maintain 1032 to attempt this problem, no wonder our solution failed. FYI, it failed for input 1534236469, encounter if yous tin give notice spot the põrnikas together with create it.

import org.junit.*; import static org.junit.Assert.*; /**  * JUnit attempt 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));           }     } 

together with hither is the trial of running these JUnit attempt instance inwards Eclipse :

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

You tin give notice encounter that lovely light-green bar, which way all 5 tests are passed.

That's all nigh how to opposite Integer inwards Java. By the way, this solution is prone to integer overflow together with volition non live expected at Leetcode.  It exclusively managed to operate past times 1028 attempt cases out of staggering 1032 tests together with failed for input 1534236469. Expected solution, inwards that case, is nix but our programme impress something else, encounter if yous tin give notice spot the põrnikas together with create it.

If yous similar to solve programming problems similar this, yous volition too bask solving next coding problems from Java Interviews :
  • How to opposite words inwards String inwards 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 discovery the missing publish inwards a sorted array inwards Java? [answer]
  • How to discovery all permutation of String inwards Java? [solution]
  • How to remove element from array without using tertiary political party library (check here)
  • How to discovery largest together with smallest publish inwards an array inwards Java (read here)
  • How to discovery 2 maximum publish on integer array inwards Java (check here)

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

Subscribe to receive free email updates:

0 Response to "How to contrary Integer inwards Java - LeetCode Solution"

Posting Komentar