8 Jul 2015

Algo #122 : ATOI

Problem Statement : 
        Implement atoi to convert string into integer.

Solution : 

Below is atoi implementation.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 public static int atoi(String in) {
  int radix = 10;
  int limit = Integer.MAX_VALUE;
  int multiplicationLimit = limit / radix;
  
  if(in==null || (in=in.trim()).equals(""))
   return 0;
  
  int result=0, i =0 , len = in.length();
  boolean isPositive=true;
  
  if (in.charAt(0) == '-') {
   i++;
   isPositive = false;
  } else if (in.charAt(0) == '+') 
   i++;
  
  while(i<len){
   char c =  in.charAt(i++);
   if(c >= '0' && c <= '9')
   {
    int digit  =  (c - '0');
    if(result < multiplicationLimit) 
     result = result * radix + digit;
    else   //result overflowing
    {
     if(isPositive)
      return Integer.MAX_VALUE;
     else
      return Integer.MIN_VALUE;
    }
   }
   else
     break;
  }
  
  if(!isPositive)
   result=-result;

  return result;
 } 

 public static void main(String[] args) {
  
  System.out.println(atoi(" -88297 248252140B12 37"));
  System.out.println(atoi(" 75 6 "));
  System.out.println(atoi("+349A756"));
 }

Please post comments and suggestions if any.
Happy Coding !! :)

No comments:

Post a Comment