Wednesday, September 9, 2015

[Math] String to Integer (atoi)

1. Example
Possibility to break => Use while loop and an IDNEX
Integer.MAX_VALUE =  2147483647
Integer.MIN_VALUE = -2147483648
Long.MAX_VALUE =  9223372036854775807
Long.MIN_VALUE = -9223372036854775808
"+" and "-"
"456"=>456


2. Implementation
Q1: LSB->MSB
A1: start from LSB to MSB and use res = res*10+ current digit
Q1: special character?
A1: trim and check valid >="0" && <="9"


public int myAtoi(String str)
{

    

     // validate the input
     if ( str == null || str.length() == 0 )   
     {
           return 0;
     }




     str = str.trim();





     // NOTE: could be all spaces
     if ( str.length() == 0)
           return 0;





     boolean negFlag = flase;
     //if ( str.charAt(0) == '-')
     //    negFlag =true; 
     // NOTE: could have no sign, so put an index
     int index = 0; 
     if ( str.charAt(0) == '-' || str.charAt(0) == '+' )
     {
          index++;
          if ( str.charAt(0) == '-')
              negFlag = true;
     }





     //// NOTE: 2147483647
     //int number = 0;
     ////for (int i = str.length()-1 ; i >= 1 ; i ++)
     ////for ( int i = 1 ; i < str.length;i++ )
     //// NOTE: couldbe no sign
     //for (int i = index; i < str.length() ; i++ )
     //{
     //    char c = str.charAt(i);
     //    if ( c >= '0' && c <='9' )
     //    {
     //          
     //          if (  i == str.length() -1 && number >= Integer.MAX_VALUE /10  )
     //             number = (negFlag==true)?Integer.MIN_VALUE:Integer.MAX_VALUE; 
     //          else if ( number == Integer.MAX_VALUE/10 )
     //          {
     //              if ( c >= '7' && c <='9' && negFlag == false)
     //                  return Integer.MAX_VALUE;
     //              else if ( c >='8' && c <='9' && negFlag ==true)
     //                  return Integer.MIN_VALUE;
     //          }
     //          else
     //             //number = number*10 + (int)c;
     //             // NOTE: chat to int - '0'
     //             number = number*10 + (int)(c - '0');
     //    }
     //    else 
     //    {
     //          // NOTE:
     //          break;
     //    }
     //}





      
     int number = 0;
     while ( index < str.length())
     {



         if ( str.charAt(index) < '0' || str.charAt(index) > '9' )
            break;
         int digit = (int) (str.charAt(index) - '0');
         



         // NOTE: -(res*10+digit) < Integer.MIN_VALUE
         if (  negFlag &&  res >  -(Integer.MIN_VALUE+digit)/10  )
               return Integer.MIN_VALUE;
         // NOTE: res*10+digit    > Integer.MAX_VALUE
         else if ( !negFlag && res >  (Integer.MAX_VALUE-digit)/10  )
               return Integer.MAX_VALUE;


       
         number = number*10+digit;
         

        

         index++;



     }









     //return number ;
     return negFalg?-number:number;



     
}
3. Similar Ones
(E) Reverse Integer
(H) Valid Number

No comments:

Post a Comment