gpt4 book ai didi

java - 将字符串转换为长整型,无内置库

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:59 24 4
gpt4 key购买 nike

我编写了 Java 代码将 String 转换为 long。但是,在处理溢出问题时,我不知道如何解决它。如果一个数字溢出,计算机认为每个数字在存储中都是合法的。 如何让程序在64位jdk下检测到实数溢出是关键问题。而且我不允许使用任何内置库,例如 parseLong 或其他库。

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,结果将无法正确存储在计算机中。

如何解决这个问题?

最佳答案

您最好的选择可能是在开始之前对输入和最小/最大数字进行字典顺序比较。

static int compare(String v1, String v2) {
boolean neg1 = v1.startsWith("-");
boolean neg2 = v2.startsWith("-");
return neg1 ? (neg2 ? -comparePositives(v1.substring(1),v2.substring(1)):-1)
: (neg2 ? 1 : comparePositives(v1, v2));
}

static int comparePositives(String v1, String v2) {
// Is one longer?
if (v1.length() != v2.length())
return v1.length() < v2.length() ? -1 : 1;

// Both empty?
if (v1.isEmpty())
return 0;

// First digit differs?
if (v1.charAt(0) != v2.charAt(0))
return v1.charAt(0) < v2.charAt(0) ? -1 : 1;

// Recurse on rest of number
return comparePositives(v1.substring(1), v2.substring(1));
}

例如使用它,如下所示:

if (compare(s, ""+Long.MIN_VALUE) == -1)
throw new NumberFormatException("Input too small");

if (compare(s, ""+Long.MAX_VALUE) == 1)
throw new NumberFormatException("Input too large");

在这里测试:http://ideone.com/HmMkJ3

请注意,代码不会检查输入的格式是否正确。我建议你先做这样的检查。 (请注意 0-0 等情况)

关于java - 将字符串转换为长整型,无内置库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26011354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com