Sunday, April 5, 2015

Java Code that converts String to Integer. Standard atoi function.

As a first thing, we need to sanitise the string.
  1. It could be null.
  2. It could have leading and trailing spaces.
  3. It could have an additional +/- symbols.
  4. It could have invalid characters, spaces and what not. 
As a next thing, for all we know the string could contain values more than Integer.MAX_VALUE. So, we don't accept strings of length more than that. 

Now, we simply pluck out each character, get it's integer value and add the corresponding exponent's according to the digit's position. We need to take caution when trying to add each characters because the string could still have a value more than Integer.MAX_VALUE. 
If we add the new value like this
    convertedInt + newValueToAdd > Integer.MAX_VALUE
it might overflow. 

So we do the opposite.
  convertedInt <= Integer.MAX_VALUE - newValueToAdd

Here is the implementation.
========================================================================

public static void main (String[] args) throws java.lang.Exception
{
String a = "2147483647";
System.out.println("Integer : " + atoi(a));
}

public static int atoi(String a) throws Exception
{
String sane = checkSanity(a);
if( sane == null )
{
throw new Exception("Not compatible");
}

if( sane.length() > 10 )
{
throw new Exception("Overflow");
}

if( sane.length() <= 0 )
{
throw new Exception("Underflow");
}

int convertedInt = 0;
int exponent = 0;
for( int i = sane.length() - 1; i >= 0 ; i-- )
{
int newDigit = Character.getNumericValue( sane.charAt(i) );

int newValueToAdd = (int) ( Math.pow(10, exponent) * newDigit );

if( convertedInt <= Integer.MAX_VALUE - newValueToAdd )
{
convertedInt += newValueToAdd;
}
else
{
throw new Exception("Overflow");
}

exponent++;
}

return convertedInt;
}

public static String checkSanity(String a)
{
// could be null
if( a == null )
{
return null;
}

// Trim leading and trailing spaces.
String b = a.trim();

// Should it have + or - symbol, consider.
String c;
if( b.charAt(0) == '+' || b.charAt(0) == '-' )
{
c = b.substring(1);
}
else
{
c = b.substring(0);
}

// could have special characters and non numbers.
for( int i = 0; i < c.length(); i++ )
{
if( ! Character.isDigit(c.charAt(i)) )
{
return null;
}
}

return c;
}
}

========================================================================

Test execute it here.

No comments:

Post a Comment