题解 | #将字符串转化为整数#

将字符串转化为整数

http://www.nowcoder.com/practice/44d8c152c38f43a1b10e168018dcc13f

import java.util.*;


public class Solution {
    /**
     * 
     * @param str string字符串 
     * @return int整型
     */
    public int atoi (String str) {
        // write code here
        int sign = 1;
        boolean has = false;
        int ans =0, pop = 0;
        for(int i = 0; i < str.length(); ++i) {
            if(str.charAt(i) == '-' && !has) {
                sign = -1;
                has = true;
                continue;
            }
            if(str.charAt(i) == '+' && !has) {
                sign = 1;
                has = true;
                continue;
            }
            if(str.charAt(i) == ' ' && !has) {
                continue;
            }
            if(str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                has = true;
                pop = str.charAt(i) - '0';
                if(ans * sign > Integer.MAX_VALUE / 10 || ans * sign == Integer.MAX_VALUE / 10 && pop * sign > 7) {
                    return Integer.MAX_VALUE;
                }
                if(ans * sign < Integer.MIN_VALUE / 10 || ans * sign == Integer.MIN_VALUE / 10 && pop * sign < -8) {
                    return Integer.MIN_VALUE;
                }
                ans = ans * 10 + pop;
            }else{
                return ans * sign;
            }
        }
        return ans * sign;
    }
}
全部评论

相关推荐

主页这么好的公司是谁在进啊:虽然很想感谢你的分享,但是此刻的嫉妒和酸气已经涌上心头,所以我撤销一下对你的感谢吧,希望你能原谅我
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务