大概有10天左右沒有練習算法編程了!還是不能放下。。。
劍指offer49題
題目描述
package test1;
public class Test49 {
public static int StrToInt(String str) {
//例如將字符串“123”轉化爲123;理解是1*10=10;10*10+2=12;12*10+3=123;
if(str==null||str.length()<1){
throw new NumberFormatException(str);
}
char first=str.charAt(0);
if(first=='-'){
return parseString(str,1,false); //符號負數的處理
}else if(first=='+'){
return parseString(str, 1, true);//符號正數處理
}else if(first>'0'&&first<'9'){
return parseString(str, 0, true);//正常處理
}else{
throw new NumberFormatException(str);//異常處理
}
}
private static int parseString(String str, int index, boolean sp) {
if(index >=str.length()){
throw new NumberFormatException(str);
}
int result = 0;
long tmp=0;
while(index<str.length()&&isDigit(str.charAt(index))){
tmp=tmp*10+str.charAt(index)-'0';//從最高位取數字,tmp=1;index=1,tmp=10+2;index=2,tmp=120+3;
//保證求出的值不超過整數的最大範圍
if(tmp>Integer.MAX_VALUE){
throw new NumberFormatException(str);
}
index++;
}
//sp=true是表示正數。sp=false則是負數
if(sp){
if(tmp>=Integer.MAX_VALUE){
throw new NumberFormatException(str);
}else{
result=(int)tmp;
}
}else{
if(tmp==Integer.MAX_VALUE){
result = 0x8000_0000;
}else{
result=(int)-tmp;
}
}
return result;
}
private static boolean isDigit(char c) {
return c >= '0' && c <= '9';
}
public static void main(String[] args) {
System.out.println(StrToInt("123"));
}
}