剑指offer_ 把字符串转换成整数
题目描述
将一个字符串转换成一个整数,字符串不是一个合法的数值则返回 0,要求不能使用字符串转换整数的库函数。
Iuput: +2147483647 1a33 Output: 2147483647 0
方法一:直接计算
1 public class Solution { 2 public int StrToInt(String str) { 3 if(str.equals("-2147483648")) 4 return -2147483648; 5 if(str==null||str.length()==0) return 0; 6 char ch[]=str.toCharArray(); 7 boolean flag = false; 8 int n = ch.length; 9 int sum = 0; 10 for(int i = 0;i<n;i++){ 11 if(i==0&&(ch[i]=='+'||ch[i]=='-')) continue; 12 if((ch[i]-'0'>9||ch[i]-'0'<0)) return 0; 13 14 } 15 if(ch[0]=='+') { 16 if(ch.length!=1) 17 ch=str.substring(1).toCharArray(); 18 else 19 return 0; 20 } 21 if(ch[0]=='-') { 22 if(ch.length!=1){ 23 ch=str.substring(1).toCharArray(); 24 flag=true;} 25 else 26 return 0; 27 } 28 for(int i=0;i<ch.length;i++){ 29 sum+=(ch[i]-'0')*Math.pow(10,ch.length-i-1); 30 } 31 if(flag) sum=-sum; 32 return sum; 33 } 34 }
方法二;
1 public class Solution { 2 public int StrToInt(String str) { 3 if (str == null || str.length() == 0) 4 return 0; 5 boolean isNegative = str.charAt(0) == '-'; 6 int ret = 0; 7 for (int i = 0; i < str.length(); i++) { 8 char c = str.charAt(i); 9 if (i == 0 && (c == '+' || c == '-')) /* 符号判定 */ 10 continue; 11 if (c < '0' || c > '9') /* 非法输入 */ 12 return 0; 13 ret = ret * 10 + (c - '0'); 14 } 15 return isNegative ? -ret : ret; 16 } 17 }

浙公网安备 33010602011771号