标签:style blog http color os io strong for
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.
算法思路:
坑比较多,没难度。开整之前建议先把str预处理一下
【注意】边界case:
全空格、全非法字符、空串<-这三种预处理之后都变成空串了。
溢出。因此先把result声明成long型。
符号处理:
两个boolean变量表示正负号,但是一旦有了某个符号,第二个符号就变成非法字符了。字符串中未出现符号,按照正号处理。
代码如下:
1 public class Solution { 2 public int atoi(String str) { 3 if(str == null || str.trim().length() == 0) return 0; 4 str = str.trim(); 5 StringBuilder sb = new StringBuilder(); 6 int length = str.length(); 7 ////preprocess,only maintain num and operater 8 for(int i = 0; i < length; i++){ 9 if(str.charAt(i) == ‘+‘ || str.charAt(i) == ‘-‘ || (str.charAt(i) <= ‘9‘ && str.charAt(i) >= ‘0‘)){ 10 sb.append(str.charAt(i)); 11 }else break; 12 } 13 length = sb.length(); 14 boolean positive = false,negative = false; 15 long res = 0; 16 for(int i = 0; i < length; i++){ 17 //the second time appearrance of operater is invalide 18 if((sb.charAt(i) == ‘+‘ || sb.charAt(i) == ‘-‘) && (positive || negative)) 19 break; 20 if(sb.charAt(i) == ‘+‘){ 21 positive = true; 22 }else if(sb.charAt(i) == ‘-‘){ 23 negative = true; 24 }else{ 25 res = res * 10 + (sb.charAt(i) - ‘0‘); 26 } 27 } 28 if(!positive && !negative) positive = true; 29 // process overflow situation 30 if(positive) return res > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) res; 31 return res > Integer.MAX_VALUE ? Integer.MIN_VALUE : (int)res * -1; 32 } 33 }
[leetcode]String to Integer (atoi),布布扣,bubuko.com
[leetcode]String to Integer (atoi)
标签:style blog http color os io strong for
原文地址:http://www.cnblogs.com/huntfor/p/3911519.html