题目:不使用Integer.parseInt(str)方法,将String类型的整数字符串转为Int类型的整数
例如将"-46570"转为-46570,将"146570"转为146570,注意,也不能使用Integer.valueOf(str).intValue();
算法一:
public class test2 {
public static void main(String args[]){
String str1 = "-46570";
System.out.println(trans(str1));
String str2 = "146570";
System.out.println(trans(str2));
}
public static int trans(String target){
String resultStr = target;
boolean flag = true;
if (target.charAt(0)=='-') {
resultStr = target.substring(1, target.length());
flag = false;
}
int result = 0;
for (int i = resultStr.length()-1,j=0; i>=0 ; i--,j++) {
result += (resultStr.charAt(i)-48)*(int)Math.pow(10, j);
}//直接将单个字符转为数字
if (flag) {
return result;
}
else {
return -result;
}
}
}
算法二:
public class test2 {
public static void main(String args[]){
String str1 = "-46570";
System.out.println(trans(str1));
String str2 = "146570";
System.out.println(trans(str2));
}
public static int trans(String target){
String resultStr = target;
boolean flag = true;
if (target.charAt(0)=='-') {
resultStr = target.substring(1, target.length());
flag = false;
}
int result = 0;
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < 10; i++) {
map.put(String.valueOf(i), i);
}
for (int i = resultStr.length()-1,j=0; i>=0 ; i--,j++) {
result += map.get(String.valueOf(resultStr.charAt(i)))*(int)Math.pow(10, j);
}//使用map查找单个字符串对应的数字
if (flag) {
return result;
}
else {
return -result;
}
}
}
可查看Integer.parseInt源码方法是怎么做的
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
public static int parseInt(String s, int radix) throws NumberFormatException {
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix + " less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix + " greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, max = s.length();
int limit;
int multmin;
int digit;
if (max > 0) {
if (s.charAt(0) == '-') {
negative = true;
limit = Integer.MIN_VALUE;
i++;
} else {
limit = -Integer.MAX_VALUE;
}
multmin = limit / radix;
if (i < max) {
digit = Character.digit(s.charAt(i++), radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
} else {
result = -digit;
}
}
while (i < max) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++), radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
if (negative) {
if (i > 1) {
return result;
} else { /* Only got "-" */
throw NumberFormatException.forInputString(s);
}
} else {
return -result;
}
}