我有一个关于使用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类实现了一个链表,并希望用我的构造函数打印出一个long值。 当我在main中打印一个long值时,它给出的数字与我作为参数输入的数字完全不同。 有人知道我的问题是什么吗?
答案 0 :(得分:1)
尝试修复构造函数:
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();
}