gpt4 book ai didi

java - 代表数字的链表

转载 作者:行者123 更新时间:2023-12-02 03:04:40 25 4
gpt4 key购买 nike

我有一个如下所示的 IntNode 类:

public class IntNode {
private int value;
private IntNode next;
public IntNode(int val, IntNode n)
{
value = val;
next = n;
}
public void setValue(int val){ value = val; }
public void setNext(IntNode n){ next = n; }
public int getValue() { return value; }
public IntNode getNext() { return next; }
}

还有另一个类,我将其命名为 BigNumber,它应该代表任何正数(大或小)。该类看起来像:

public class BigNumber {

private IntNode list;
//copy constructor.
public BigNumber(BigNumber other){
list = null;
for(IntNode p=other.list; p!=null; p=p.getNext())
list = new IntNode(p.getValue(), list);
}

//Constructor that takes string of a number and puts every digit in the linked list. if the string contains any char that is not digit, the linked list should be: 0->null.
public BigNumber(String num){
list = null;
if(stringIsNum(num)){
for(int i=0; i<num.length(); i++){
list = new IntNode((int)num.charAt(i),list);
}
}
else{
list = new IntNode(0, list);
}
}

private boolean stringIsNum(String num){
for(int i=0; i<num.length(); i++){
if(!(num.charAt(i)>='0' && num.charAt(i)<='9'))
return false;
}
return true;
}

public String toString(){
String s = "";
for(IntNode p=list; p!=null; p=p.getNext())
s+=p.getValue()+"";
return s;
}
}

这个类中的问题是,当我想要打印时,假设字符串是“123”,它会打印类似 515049 的内容,而不是实际的数字 321(它应该向后打印数字)。有什么问题吗?

最佳答案

您正在将 char 转换为 int。这给出了字符的代码点,而不是您想要的值。例如:(int) '1' = 49

使用Integer.parseInt(num.charAt(i))代替(int)num.charAt(i)

关于java - 代表数字的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41897180/

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