package solution; import java.util.Scanner; public class StrToInt { public static void main(String[] args) { System.out.println(StrToInt("")); } public static int StrToInt(String str) { if (str == null || str=="" || str.length()==0) return 0; //1.先将字符串转换成字符数组 char[] num = str.toCharArray(); //2.对字符数组中的每一位进行判断 int base = 1; if (num[0] == ‘-‘ && num.length > 1) { base = -1; } else if (num[0] == ‘+‘ && num.length > 1) { base = 1; } else if (!((num[0] >= ‘0‘) && (num[0] <= ‘9‘))) { return 0; } int sum = 0; int count = 0; for (int i = num.length - 1; i > 0; i--) { if(num[i] >= ‘0‘ && num[i] <= ‘9‘){ sum += base * Integer.parseInt(String.valueOf(num[i])) * Math.pow(10, count); count++; }else{ return 0; } } if(num[0] >= ‘0‘ && num[0] <= ‘9‘){ sum += base * Integer.parseInt(String.valueOf(num[0])) * Math.pow(10, count); } return (int)sum; } }
原文:https://www.cnblogs.com/ustc-anmin/p/11396458.html