昨天无意中浏览到Magic的博客,发现里面又很多的好东西,讲的是J2EE学习备忘录。里面有很多关于Java基础知识的文章,在算法这个篇章下有一篇是关于不用系统函数将字符串转化为数字,正好前几天的面试我遇到了这个问题,还有些问题没有搞明白,也知道自己的缺点是缺少动手巧代码。结合前几天研究的parseIn()方法的源代码,贴出来让大家看看。里面还有些问题,虽然可以处理各种进制的转换,但是却不能手动输入是多少进制,因为这里有涉及到字符串转数字的操作,希望大家能帮帮忙,看看还有什么更好的办法!
运行结果:
1A
26
-1a
-26
+1d
29
bd
189
gfgh
java.lang.NumberFormatException: not number
at StringToInt.StringToInt(StringToInt.java:41)
at StringToInt.main(StringToInt.java:84)
import java.util.*;
public class StringToInt{
public static int StringToInt(String str,int radix){
if(str==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 start=0;//数字开始位置"+","-"
int len=str.length();//字符串的长度
int limitLeft;//边界值
int digit;//当前字符表示的数字
if(len>0){
if(str.charAt(0)=='-'){//开始字符为负号
negative=true;
limitLeft=Integer.MIN_VALUE;
start++;
}
else if(str.charAt(0)=='+'){//开始字符为正好
negative=false;
limitLeft=-Integer.MAX_VALUE;
start++;
}
else{
limitLeft=-Integer.MAX_VALUE;
}
if(start<len){
digit=Character.digit(str.charAt(start++),radix);
//对于给定的基数,如果是合法的字符(可以转化为数字),
//返回该数字值,否则返回-1.比如digit('3',10)返回3,digit('a',10)返回-1.
if(digit<0){
throw new NumberFormatException("not number");
}else{
result=-digit;
}
}
while(start<len){
digit=Character.digit(str.charAt(start++),radix);
if(digit<0){
throw new NumberFormatException("not number");
}
if(result<(limitLeft/radix)){
throw new NumberFormatException("overflow");
}
result*=radix;
if(result<(limitLeft+digit)){
throw new NumberFormatException("overflow");
}
result-=digit;
}
}
else{
throw new NumberFormatException("exception");
}
if(negative){
if(start>1)
return result;
else
throw new NumberFormatException("not number");
}
else{
return -result;
}
}
public static void main(String args[]){
while (true) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
int radix=16;
try {
System.out.println(StringToInt.StringToInt(str,radix));
}
catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
}
运行结果:
1A
26
-1a
-26
+1d
29
bd
189
gfgh
java.lang.NumberFormatException: not number
at StringToInt.StringToInt(StringToInt.java:41)
at StringToInt.main(StringToInt.java:84)