String to Integer

来源:互联网 发布:单片机应用技术 编辑:程序博客网 时间:2024/05/01 15:29

Question:

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.


//********** Hints ************

//*****************************


Solution:

public class Solution {
    public int atoi(String str) {
        double i = 0;
        boolean pos = true;
        boolean front = true;
        boolean frontsign = true;
        
        for(int j=0; j<str.length(); j++){
            char c = str.charAt(j);
            
            if(c == ' ' && front){
                continue;
            }
            
            else if(c == '-' && frontsign){
                pos = false;
                front = false;
                frontsign = false;
            }
            
            else if(c == '+' && frontsign){
                front = false;
                frontsign = false;
                continue;
            }
            
            else if(c >='0' && c <= '9'){
                i = (i*10 + (c - 48));
                front = false;
            }
            
            else{
                break;
            }
        }
        
        if(!pos){
            i = -i;
        }
        
        if(i>2147483647)
            return 2147483647;
            
        if(i<-2147483648)
            return -2147483648;
        
        return (int)i;
    }
}


0 0