首页 > 代码库 > [leetcode]String to Integer (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.
算法思路:
坑比较多,没难度。开整之前建议先把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 invalide18 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 situation30 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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。