首页 > 其他 > 详细

String to Integer (atoi)

时间:2015-05-20 02:25:44      阅读:126      评论:0      收藏:0      [点我收藏+]

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.

?

public class Solution {
	/*
	 * 注意考虑正负号、溢出、非法字符、空格等等
	 * */
    public int myAtoi(String str) {
        double num = 0;
        str = str.trim();
        int digit = 0;
        boolean flag = false;
        for (int i = str.length()-1; i >= 0; i--) {
        	char ch = str.charAt(i);
        	if (ch<=‘9‘ && ch>=‘0‘) {
        		num += (ch-‘0‘) * (int)Math.pow(10, digit);
        		digit++;
        	} else if (ch==‘+‘ || ch==‘-‘) {
        		if (flag) {
        			return 0;
        		}
        		flag = true;
        		if (ch==‘-‘) {
        			num = -num;
        		}
        	} else {
        		num = 0;
        		flag = false;
        		digit = 0;
        	}
        }
        if (num > Integer.MAX_VALUE) {
        	return Integer.MAX_VALUE;
        }
        if (num <= Integer.MIN_VALUE) {
        	return Integer.MIN_VALUE;
        }
        return (int) num;
    }
}

?

String to Integer (atoi)

原文:http://hcx2013.iteye.com/blog/2212641

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!