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.
实现字符串转换为int型整数并不难,只是有好多中输入情况需要考虑,容易造成遗漏。首先看一下c++ 中atoi的定义:
-----------------------------------
int atoi (const char * str);
int
.
int
value.
int
, it causes undefined behavior. See strtol for a more robust cross-platform alternative when this is a possibility.
------------------------------------------
可以看出需要注意的有以下几点:
考虑了上面几方面,代码就可以AC了。
public class String_To_Integer { //java public static int atoi(String str) { int haveMinus = 1; long result = 0; if(str == null || str.trim().isEmpty()) return 0; //chech + - str = str.trim(); if(str.charAt(0) == '-'){ str = str.substring(1); haveMinus = -1; }else if(str.charAt(0) == '+') str = str.substring(1); //check num for(int i = 0;i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'; i++){ result = result*10 + (str.charAt(i)- '0'); } //deal overflow if(result > 2147483647 && haveMinus == 1) return 2147483647; if(result > 2147483647 && haveMinus == -1) return -2147483648; return haveMinus*(int)result; } public static void main(String [] args){ System.out.println(String_To_Integer.atoi("2147483648")); } }
[leetcode]String to Integer (atoi)
原文地址:http://blog.csdn.net/chenlei0630/article/details/40714065