码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--String to Integer (atoi)

时间:2014-12-19 22:02:39      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

题目:

技术分享

解决方法:

public class Solution {
    public int atoi(String s) {
        int MAX=2147483647;
        int MIN=-2147483648;
        s = s.trim();//1.去除空格
        long value = 0;
        int flag = 1;
        for (int i = 0; i < s.length(); i++) {
            if (i == 0 && (s.charAt(i) == '+' || s.charAt(i) == '-')) {//2.正负号
                if (s.charAt(i) == '-') {
                   flag = -1;
                }
                continue;
            }
            if (s.charAt(i) < '0' || s.charAt(i) > '9') break;//3.遇见0-9以外字符退出循环
            value = 10 * value + s.charAt(i) - '0';
            long temp=value*flag;
            if(temp>MAX){value=MAX;break;}else if(temp<MIN){value=MIN;break;}//4.Int溢出中断
        }
        value =  value * flag;
        return (int) value;
    }
}


LeetCode--String to Integer (atoi)

标签:

原文地址:http://blog.csdn.net/wj512416359/article/details/42031773

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!