String to Integer (atoi)

获取string中单一的值
String a="中国";
char b=a.charAt(0);


    public static int myAtoi(String str) {
        long result = 0;
        int m = 0;//index of str
        if(str.length() < 1){ //注意可以输入一个空的‘’两个引号之间啥都没 空格都没
            return 0;
        }
        str = str.trim(); //整形整掉所有前面连贯的空格 如’   10’
        if (str.charAt(0) == '+' || str.charAt(0) == '-'){//处理符号以及第一个是空的话
            m = m+1;
        }
        for(;m<str.length();m++){
            if(str.charAt(m) < '0' || str.charAt(m) >'9'){ //atoi规定 数字后面的符号不影响数字 如"  -0012a42" 转化为-12
                return (int) result;
            }
            int item = 1;//用于处理负数
            if  (str.charAt(0) == '-'){ //注意负数
               item = -1;
            }

            result = result*10 + item*(str.charAt(m) - '0');// 利用ascii的差值求数
            if (result > Integer.MAX_VALUE)//溢出处理 规定 If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
        return Integer.MAX_VALUE;
 
            if (result < Integer.MIN_VALUE)
        return Integer.MIN_VALUE;
        }

        return (int) result;
    }
}     


标准答案(其实思路一样 标准答案的structure整齐一点)
public int atoi(String str) {
    if (str == null || str.length() < 1)
        return 0;
 
    // trim white spaces
    str = str.trim();
 
    char flag = '+';
 
    // check negative or positive
    int i = 0;
    if (str.charAt(0) == '-') {
        flag = '-';
        i++;
    } else if (str.charAt(0) == '+') {
        i++;
    }
    // use double to store result
    double result = 0;
 
    // calculate value
    while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
        result = result * 10 + (str.charAt(i) - '0');
        i++;
    }
 
    if (flag == '-')
        result = -result;
 
    // handle max and min
    if (result > Integer.MAX_VALUE)
        return Integer.MAX_VALUE;
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值