atoi() in Java

with 8 comments

Problem: Write a function to convert an ASCII string to integer, similar to atoi() function of C++.

Solution: The solution is too simple, it's simple checks for erroneous inputs that makes writing such a function fun.

Update: You may also want to refer the implementation of parseDouble() method in Java

Here is my attempt at this classic problem.

package com.sangupta.keepwalking;

public class AsciiToInteger {
 
 public static void main(String[] args) {
  AsciiToInteger instance = new AsciiToInteger();
  int x = instance.atoi("-683");
  System.out.println("Conversion is: " + x);
 }

 private int atoi(String number) {
  // check for NULL or empty
  if(number == null || number.trim().length() == 0) {
   throw new IllegalArgumentException("Number cannot be null/empty.");
  }

  // create a variable to store the result
  int result = 0;
  
  // trim the number
  number = number.trim();
  
  // check for sign as the first character
  boolean negate = false;
  char sign = number.charAt(0);
  
  if(sign == '+' || sign == '-') {
   if(sign == '-') {
    negate = true;
   }
   
   number = number.substring(1);
  }
  
  int length = number.length();
  for(int index = 0; index < length; index++) {
   char digit = number.charAt(index);
   
   // sanitize the digit
   if(!(digit >= '0' && digit <= '9')) {
    throw new IllegalArgumentException("Number contains characters other than digits at index " + index);
   }
   
   digit = (char) (digit - '0');
   
   result += (digit * Math.pow(10, (length - index - 1)));
  }
  
  // if negative, do it
  if(negate) {
   result = 0 - result;
  }
  
  // return the final result
  return result;
 }

}

written by Sandeep Gupta

Saturday, October 2, 2010 at 11:05 PM

Comments

8 responses to ' atoi() in Java '

  • thanks for your easy to understand example

  • Hi,
    I know this is a very old post. Just wanted to quote a small bug. If you input with a '-' symbol or '+' symbol you receive output as 0 which is wrong.
    You can add another line to check the length of the number variable and validate the same to throw an exception.

  • @Venkat: Thanks for reporting. I will regress and provide the fix accordingly.

    ~ Sandeep

  • wats de output for this coding ...? I din get any output run time error hepl me !!

  • Hi. i have a few queries the coding:
    1> atoi must convert string to number and if we provide input that has alphabets, it should just neglect that and give away the numeric part i hunch but this code throws an error..
    2> wanna know the purpose behind : digit = (char) (digit - '0');
    3> if the input has 0 then its being discarded in the output...

  • @Freddiee: Can you please post some sample code so that I can debug.

    @Rohith:

    1) In case a number has alphabets, there are 3 choices
    a) You can either return the number parsed till that point
    b) Or, you can throw an error
    c) Or, you can continue to parse

    Throwing an error works for library functions, as this will entail the callee function to make sure that they don't parse garbage. Say, if the string passed was "ab" to which you returned a zero. Now, think if a foreign key in the database was being stored as string, but to be used, was being converted from atoi(). In such a scenario, you will hit the wrong record (with id=0) than finding the corrupt record.

    It is usually a convention to throw error for all possible cases to callee in library functions.

    2) When you do a digit - '0', Java does this operation as integers and not char/short or anything. Thus, it has to be converted back to char to keep it in bounds (though an unnecessary check in this case, but a useful check to indicate that this is intentional per coding).

    3) When you say a '0' is being discarded, can you please provide the sample input string and output so that I can take a look.

    ~ Sandeep

  • Am sorry... forget about the zero being discarded issue i tole earlier. There s something i wanna know:
    > digit = (char) digit-'0';
    the final result of arithmetic operation will be an int so u parsed it to char . Why is it used at all.. as u said, it was not useful though. But i tried to run the code by commenting that line and it yielded different results.
    For eg: I/P = 101 , O/P = 101
    After commenting : O/P = 5429

  • number = number.substring(1);

    this will cause an out-of-bound exception on input such as "+" or "-".

Post Comments