(atoi)Leetcode第八题_String to Integer (atoi)

String to Integer (atoi)

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.

这一题打该意思是将一个字符串转换成一个整型数,大概就是类似于atoi()这个函数的功能,要考虑很多的特例而已。

函数名: atoi

功 能: 将字符串转换成整型数;atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负号才开始做转换,而再遇到非数字或字符串时(’\0’)才结束转化,并将结果返回(返回转换后的整型数)。

这是atoi函数的功能,照着这个功能实现既可。但要考虑溢出啊,空白字符串啊这一大片的问题。

在这里,我处理溢出没有使用常规的方法,而是把res定义为long,然后返回时强转成int了,不知道算不算作弊啊。

public class Solution {

    private static final int INT_MAX = 2147483647;
    private static final int INT_MIN = -2147483648;
    public static int myAtoi(String str) {
        int i = 0;
        int flag = 0;
        long res = 0;
        if (str.equals("")) {
            return 0;
        }
//      跳过字符串前的空白字符
        while(str.charAt(i)==' '){
            i++;
            if (i>str.length()-1) {
                return 0;
            }
        }
//      遇到+ - 符合开始的数字
        if (str.charAt(i)=='+' || str.charAt(i)=='-') {
//          如果是-,则标记为1
            if (str.charAt(i)=='-') {
                flag = 1;
            }
            i++;
        }
//      将字符转换为数字
        while (str.charAt(i)>='0'&&str.charAt(i)<='9') {
//          处理溢出的情况
            if (res*10 + str.charAt(i) - '0'>INT_MAX && flag == 0) {
                return INT_MAX;
            }
            if (res*10 + str.charAt(i) - '0'-1>INT_MAX && flag == 1) {
                return INT_MIN;
            }
            res = res*10 + str.charAt(i) - '0';
            i++;
            if (i == str.length()) {
                break;
            }
        }
        if (flag==1) {
            res = res*-1;
        }
        return (int)res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值