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

来源:互联网 发布:杭州市行知幼儿园招聘 编辑:程序博客网 时间:2024/05/17 03:26

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;    }}
0 0