[ 问题: ]
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.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
更多精彩内容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
[ 分析: ]① 字符串为空或空字符串, 返回0;② 忽略字符串前后空格;③ 第一个字符如果为'+'或'-'先记住它, 接着往下读, 如果读到的是数字, 则开始处理数字, 如果为其他特殊字符, 停止读取, 返回结果;④ 处理过程中, 如果转换出的值超出了int类型范围, 那么返回int的最大值或最小值.
[ 解法: ]
public class Solution { private final static int INT_MAX = 2147483647; private final static int INT_MIN = -2147483648; public int atoi(String str) { int i = 0, flag = 1; // flag为正负标记符 long result = 0; // 转换之后可能变成long型 if (str == null || str.length() == 0) { return 0; // step 1 } char[] ch = str.trim().toCharArray(); if (ch.length == 0) { return 0; // step 2 } if (ch[i] == '+' || ch[i] == '-') { flag = ch[i++] == '+' ? 1 : -1; // step 3 } while (i < ch.length && ch[i] >= '0' && ch[i] <= '9') { result = result * 10 + (ch[i++] - '0'); // '0'到'9' askii码为48~57 if (result * flag < INT_MIN || result * flag > INT_MAX) { return result * flag < INT_MIN ? INT_MIN : INT_MAX; // step 4 } } return (int) result * flag; } public static void main(String[] args) { System.out.println(new Solution().atoi("999")); } }
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索字符串
, int
, return
, whitespace
, 字符串ip转换整形
, flag
, atoi
, returned non zero
, 字符串转整形
, The
, 字符串转int
, atoi()
Characters
string、string to int、string to json、string to date、string to byte[],以便于您获取更多的相关知识。