String to Integer
String to Integer
问题:
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.
思路:
只是需要考虑的corner case多一些,思路很简单
我的代码:
public class Solution { public int myAtoi(String str) { if(str==null || str.length()==0 || str.trim().length()==0) return 0; str = str.trim(); boolean isPlus = true; if(str.charAt(0) == '-') { isPlus = false; str = str.substring(1); } else { if(str.charAt(0) == '+') str = str.substring(1); } long rst = 0; for(int i=0; i<str.length(); i++) { char c = str.charAt(i); if(isValidNum(c)) { rst = rst*10 + (c-'0'); long tmp = (isPlus ? rst : rst*-1); if(tmp>Integer.MAX_VALUE) return Integer.MAX_VALUE; if(tmp<Integer.MIN_VALUE) return Integer.MIN_VALUE; } else break; } rst = (isPlus ? rst : rst*-1); return (int)rst; } public boolean isValidNum(char c) { return c<='9' && c>='0' ? true : false; } }
posted on 2015-04-28 09:44 zhouzhou0615 阅读(149) 评论(0) 编辑 收藏 举报