您的位置:首页 > 编程语言 > Java开发

自定义实现类似Java的Integer.parseInt(String str)函数

2014-05-15 21:09 429 查看
public static int stringToInteger(String str) {
if (str == null || str == "") {
throw new RuntimeException("not a valid number");
}
byte[] bytes = str.getBytes();
int digits = bytes.length;
int sum = 0;
for (byte b : bytes) {
if (b < 48 || b > 57) {
throw new RuntimeException("not a valid number");
}
int dueNum = mapStrNumByteToNum.get((b+""));
sum += dueNum * Math.pow(10, --digits);
}
return sum;
}

public static Map<String, Integer> mapStrNumByteToNum = new HashMap<String, Integer>();
static {
for (int i = 0; i < 10; i++) {
mapStrNumByteToNum.put((48 + i)+"", i);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: