我編寫了Java代碼將String
轉換爲long
。但是,在處理溢出問題時,我沒有線索如何解決它。如果一個數字溢出,計算機相信每個數字在存儲中都是合法的。 如何讓程序用64bit jdk檢測實數溢出是關鍵問題。而且我不允許使用任何內置庫,如parseLong或其他。將字符串轉換爲Long,沒有內置庫
public static long strTolong(String s){
//error checking
if(s == null) return 0;
s = s.trim();//remove all space character
boolean neg = false;//judge the number is negative or positive
int pos = 0 ; //index of string
long result = 0;
//check positive or negative
if(s.charAt(pos) == '-'){
neg = true;
pos++;
}else if(s.charAt(pos) == '+') pos++;
//calculate result
while(pos<s.length()){
if(s.charAt(pos) >='0' && s.charAt(pos) <='9'){
result = result*10+(s.charAt(pos) - '0');
}else
break;
pos++;
}
if(neg) result =-result;
//check overflow
if(result >Long.MAX_VALUE) {
return Long.MAX_VALUE;
}
if(result<Long.MIN_VALUE){
return Long.MIN_VALUE;
}
return result;
}
如果數據大於long.maxvalue
,結果不能被正確地存儲在計算機中。
如何解決這個問題?
「Long.parseLong(」102「);'?是什麼問題? – 2014-09-24 07:49:54