Skip to main content

Program to convert String to Integer without using Integer.parseInt()

Program : Convert a String to an Integer without using parseInt() method.
We have to convert a String suppose "12345" to its equivalent integer value that is 13245 without using the parseInt() method. We need to check if the number is positive or negative and convert accordingly.
import java.util.Scanner;

import java.util.Scanner;

class Test{

public static void main(String args[]){
System.out.println("Enter the string to be converted to integer number ");
System.out.println(new Test().stringToInteger(new Scanner(System.in).next()));
}

public int stringToInteger(String str){
int number = 0,itr=0;
boolean flag = false;

if(str.charAt(0) == '-'){
flag = true;
itr = 1;
}

for(; itr <=str.length()-1 ; itr++){
char digit = str.charAt(itr);
number += Math.pow(10, str.length() - itr -1) * (digit-48);
}
if(flag)
return -number;
else
return number;
}

}
Enter the string to be converted to integer number 
12345
12345

Enter the string to be converted to integer number
-12345
-12345
In the above program we traverse the string from first to last and find the power of 10 that is equal to the number of digits that are to the right of it and multiply it by the digit itself. For example
9     = 10^0 * 9 = 9
87   = 10^1*8 + 10^0*7 = 87
751 = 10^2*7 + 10^1*5 + 10^0*1 = 751
But when the number is negative i.e starts with a '-' sign, we find the number in the same form but change the sign of the number at the end.

Comments