gpt4 book ai didi

java - 在 Java 中使用 toString 打印 Long 值

转载 作者:行者123 更新时间:2023-12-01 13:06:10 25 4
gpt4 key购买 nike

我有一个关于使用 toString 方法打印长值的问题。

我的代码是:

public class LinkedLargeInteger {

private class Node {

private int data;
private long dat;
private Node next;

private Node(int data, Node next) {
this.data = data;
this.next = next;
}

private Node(int data) {
this(data, null);
}

private Node() {
data = 0;
next = null;
}

private Node(long dat, Node next) {
this.dat = dat;
this.next = next;
}

private Node(long dat) {
this(dat, null);
}

}

private Node head;
private Node tail;
private int size;
private String largeString;
private int largeInt;
private long largeLong;

public LinkedLargeInteger(long largeLong) {
String s = Long.toString(largeLong);
head = new Node();
tail = head;
size = 0;
for (int i = 0; i < s.length(); i++) {
tail.next = new Node(Long.parseLong(s), null);
tail = tail.next;
size++;
}
}

@Override
public String toString() {
StringBuilder builder = new StringBuilder();
Node current = head.next;
for (int i = 0; i < this.size; i++) {
builder.append(i + 1);
current = current.next;
}
return builder.toString();
}

public static void main(String[] args) {
LinkedLargeInteger numLong = new LinkedLargeInteger(100000000000L);
System.out.println(numLong);
}
}

我已经用我的 Node 类实现了一个链表,并想用我的构造函数打印出一个长值。当我在 main 中打印一个长值时,它给出的数字与我作为参数输入的数字完全不同。有人知道我的问题可能是什么吗?

最佳答案

尝试修复构造函数:

public LinkedLargeInteger(long largeLong) {
String s = Long.toString(largeLong);
head = new Node();
tail = head;
size = 0;
for (int i = 0; i < s.length(); i++) {
// You were putting the whole number, not the digits
tail.next = new Node(Long.parseLong(String.valueOf(s.charAt(i))), null); // <<==
tail = tail.next;
size++;
}
}

还有 toString:

public String toString() {
StringBuilder builder = new StringBuilder();
Node current = head.next;
for (int i = 0; i < this.size; i++) {
builder.append(current.dat); // <<==
current = current.next;
}
return builder.toString();
}

关于java - 在 Java 中使用 toString 打印 Long 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23252434/

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