Implement Integer.parseInt()



Implement parseInt method.

This is an interview question, Company:Adobe.


init result with 0
for each character in string do this
result = result * 10
//to increment the number of digits so that new digit can be added at last(right most) position.
get the digit from the character ('0' is 48 ASCII (or 0x30), so just subtract that from the character ASCII code to get the digit) add the digit to the result

return result
package com.meritmix.blog.algo;

public class ParseInteger {

 public int parseInt(String s) {
     
   int res = 0; //initialize the result with 0

      int[] arr = new int[s.length()];
      try {
          for (int i = 0; i < s.length(); i++) {
              arr[i] = s.trim().charAt(i);
          }

          try {
              for (int i = 0 ; i < arr.length ; i++) {
                  if ((arr[0] - 48) < 0 || (arr[i] - 48) >= 10) {
                      throw new NumberFormatException();
                  } else {
                      res *=10; //multiply with 10 to increment the the digits in number 
                                //and make position for last digit
                      res =res + (arr[i] - 48); // add the new digit at last position
                  }
              }
              //System.out.println(res);
          } catch (NumberFormatException n) {
              System.out.println("Enter only numbers .");
          }

      } catch (StringIndexOutOfBoundsException ex) {
          System.out.println("Don't enter a space!");
      }

      return res;
 }
 
 public static void main(String[] args) {
  //test your method
  System.out.println(new ParseInteger().parseInt("345"));
 }
}



Output:
345

No comments:

Post a Comment