Monday, 2 May 2016

How to implement Integer.parseInt() method ?


The method must produce :

  • 12345 for "12345"
  • -12345 for "-12345"
  • Error for Alphanumeric input string


Algorithm
int i = 0, number = 0;
char[] value = inputStr.toCharArray();

// Check for -ve number, and set the flag
boolean isNegative = false;
if (value[0] == '-') {
    isNegative = true;
    i = 1;
}

// iterate each character 
while(i < value.length) {
    // Pick each character
    char ch = value[i++];
    int place_value = ch - '0';

    // Check for digit and form the number
    if (place_value>=0 && place_value<=9) {
       number *= 10;
       number += (ch - '0');
    } else {
       System.out.println("Wrong input format!!");
         throw new ParseException("String to int parse",-1);
     }
}

// For -ve number, Negate the number
if(isNegative) {
     number = -number;
}

return number;

No comments:

Post a Comment

Note: only a member of this blog may post a comment.