Friday, 8 September 2017

Converting String to Integer without using any Standard Library in JAVA

This question can be asked in both service and product based company as well.
Suppose you are given a String like "12345" and after converting it should be "12345".
Normally using standard library we can convert this using Integer.parseInt("") or Integer.valueOf("").

Without using standard library, we will find out ASCII code of each character and subtract it with '0' which will give current int value and finally multiply by 10 to get actual result.

Initially we will check it starts with negative or not, if negative then substract the result from 0 at last else do nothing.

Input: "12345"
Output: 12345

Input: "-12345"
Output: -12345

Sample Code:

/**
 * 
 * @author Sourin M
 *
 */
public class StringToInteger {

public static void main(String[] args) {

String number="-1234567";
System.out.println("Number is: "+ getNumber(number));

}
public static int getNumber(String number) {
   int result = 0;
   boolean isNegative=false;
   if(number.charAt(0)=='-')
   {
    isNegative=true;    
   }else
   {
    result=number.charAt(0)-'0';
   }
   for (int i = 1; i < number.length(); i++) {
    result = result * 10 + number.charAt(i) - '0';
   }
   if(isNegative)
    result=0-result;
   return result;

}



}

No comments:

Post a Comment

Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface. A...