Java將String轉(zhuǎn)為Int
用Java寫一段將字符串轉(zhuǎn)成整數(shù)的函數(shù)
要求:不要調(diào)用str2int,parseInt等轉(zhuǎn)換函數(shù)元潘。按位讀取字符串里的字符進行處理將字符串轉(zhuǎn)化為整數(shù),給定的輸入一定是合法輸入不包含非法字符呀闻,字符串頭尾沒有空格酝掩,考慮字符串開頭可能有正負號。
/**
* 字符串轉(zhuǎn)數(shù)組
*
* @author shenjg
* @date 2019/07/14
**/
public class String2Int {
public static void main(String[] args) {
String str = "-623456";
System.out.println(str2int(str));
}
/**
* String類型轉(zhuǎn)換為int
*
* @param string
* @return
*/
private static int str2int(String string) {
// 空值判斷
if (StringUtils.isEmpty(string)) {
return 0;
}
// 遍歷數(shù)組位置
int index = 0;
// 正負標(biāo)識
int sign = 1;
char[] arr = string.toCharArray();
if (arr[0] == '-') {
sign = -1;
index++;
}
if (arr[0] == '+') {
index++;
}
long result = 0L;
for (; index < arr.length; index++) {
int number = char2int(arr[index]);
number = number * getDigit(arr.length - index, 1);
result = result + number;
if (result >= Integer.MAX_VALUE) {
break;
}
}
// 如果數(shù)據(jù)超限,則返回數(shù)據(jù)極限值
if (result * sign <= Integer.MIN_VALUE) {
System.out.println("數(shù)據(jù)非法饼暑,超出int最小數(shù)值");
return Integer.MIN_VALUE;
}
if (result * sign >= Integer.MAX_VALUE) {
System.out.println("數(shù)據(jù)非法,超出int最大數(shù)值");
return Integer.MAX_VALUE;
}
return (int) result * sign;
}
/**
* char類型轉(zhuǎn)int
*
* @param cha
* @return
*/
private static int char2int(char cha) {
return cha - '0';
}
/**
* 獲取位數(shù)
*
* @param length
* @param digit
* @return
*/
private static int getDigit(int length, int digit) {
if (length == 1) {
return digit;
}
digit = digit * 10;
return getDigit(length - 1, digit);
}
}