面試題:不用Java內建函式把String型別轉int型別
阿新 • • 發佈:2019-01-28
面試中遇到一道演算法題:不採用java的內建函式,把String型別轉換為int型別。現採用兩種方法實現(直接上程式碼):
package com.haiwi.test;
public class AtoiTest {
public static void main(String[] args) throws Exception {
String s = "-011134";
System.out.println("轉換前的字串:" + s);
System.out.println("atoi1轉換後的字串:" + atoi1(s));
System.out.println("atoi2轉換後的字串:" + atoi2(s));
}
/**
* 不用java內建函式,將String字串轉換為數字
* @param s
* @return
* @throws Exception
*/
public static int atoi1(String s) throws Exception {
if (s == null || s.length() == 0) {
throw new Exception("要轉換的字串為空,無法轉換!");
}
int retInt = 0;
int[] num = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '-':
num[i] = -1;
break;
case '0':
num[i] = 0;
break;
case '1':
num[i] = 1;
break;
case '2':
num[i] = 2;
break;
case '3' :
num[i] = 3;
break;
case '4':
num[i] = 4;
break;
case '5':
num[i] = 5;
break;
case '6':
num[i] = 6;
break;
case '7':
num[i] = 7;
break;
case '8':
num[i] = 8;
break;
case '9':
num[i] = 9;
break;
default:
throw new Exception("要轉換的字串格式錯誤,無法轉換!");
}
}
for (int i = 0; i < num.length; i++) {
if (num[i] < 0 && i > 0) {
throw new Exception("要轉換的字串格式錯誤,無法轉換!");
}
if (num[i] < 0) {
continue;
}
retInt += Math.pow(10, num.length - i - 1) * num[i];
}
if (num[0] == -1) {//代表負數
retInt = -retInt;
}
return retInt;
}
/**
* 不用java內建函式,將String字串轉換為數字
* @param s
* @return
* @throws Exception
*/
public static int atoi2(String s) throws Exception{
int retInt = 0;
if (s == null || s.length() == 0) {
throw new Exception("要轉換的字串為空,無法轉換!");
}
boolean isNegative = false;
for (int i = 0; i < s.length(); i++) {
if (i==0) {
if(s.charAt(i)=='-'){
isNegative = true;
continue;
}
}else{
if(s.charAt(i)>'9' || s.charAt(i)<'0'){
throw new Exception("要轉換的字串格式錯誤,無法轉換!");
}
}
retInt *=10;
retInt += s.charAt(i) - '0';
}
return isNegative ? -retInt : retInt;
}
}