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

java梳理-给一个字符串类型的数字,不调用java直接转的API写一个方法转换出来

2016-04-11 18:25 746 查看
65、给一个字符串类型的数字,不调用java直接转的API写一个方法转换出来看一眼题目,习惯了用Integer.parseInt直接处理。
public static int StrtoNum(String str){
int result =0;
if(str== null||str.equals(""))
throw new NumberFormatException("null");
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (c >= '0' && c <= '9') {
result = result * 10 + (int) (c - '0');
} else {
throw new IllegalArgumentException("s中只能包含数字");
}
}
return result;
}
如果按照ascii码判断,修改如下:
public static byte charToByteAscii(char ch){
byte byteAscii = (byte)ch;
return byteAscii;
}
public static int ByteAsciitoNum(int ascii){
if(ascii>=48&&ascii<=57)
{
return ascii-48;
}
else{
throw new IllegalArgumentException("非数字区");
}
}
public static int StrtoNum2(String str){
int result =0;
if(str== null||str.equals(""))
throw new NumberFormatException("null");
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
int ascii =charToByteAscii(c);
if (ascii >= 48 && ascii <= 57) {
result = result * 10 + ByteAsciitoNum(ascii);
} else {
throw new IllegalArgumentException("s中只能包含数字");
}
}
return result;
}
最后还是看看jdk源码怎么实现的吧;
public static int parseInt(String s, int radix)
throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/

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, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;

if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);

if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// 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);
}
return negative ? result : -result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: