先来看一道LeetCode的题目:2. 两数相加
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
这是LeetCode上一道很简单的题目,他是用链表来表示数字然后来用来做加法运算,在做加法的时候,我们只需要将最低位相加,然后往高位慢慢计算就能够很容易的得到最终的结果,他的示例解答如下:
public class Topic2 {
public static void main(String[] args) {
ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4, new ListNode(1))));
System.out.println(new Topic2().addTwoNumbers(l1, l2));
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode listNode = new ListNode(0);
ListNode curListNode = listNode;
boolean isCarry = false;
while (true) {
int sum = 0;
if (isCarry) {
sum = getVal(l1) + getVal(l2) + 1;
} else {
sum = getVal(l1) + getVal(l2);
}
if (sum > 9) {
curListNode.val = sum - 10;
isCarry = true;
} else {
curListNode.val = sum;
isCarry = false;
}
l1 = l1 == null ? null : l1.next;
l2 = l2 == null ? null : l2.next;
if (l1 == null && l2 == null) {
if (isCarry) {
curListNode.next = new ListNode(1);
}
break;
}
ListNode nextListNode = new ListNode(0);
curListNode.next = nextListNode;
curListNode = nextListNode;
}
return listNode;
}
private int getVal(ListNode listNode) {
return listNode == null ? 0 : listNode.val;
}
}
这道题目的解答很简单,但是给了我们一个解决工作中一个问题的思路:用链表来表示数值无限膨胀的数字。
那么我们根据这个思路来简单实现一个这样的链表结构。
首先关于链表的设计,由于加法运算是从低位像高位运算,而减法运算是相反的,所以我们将链表设计为双链表。
考虑到之后的运算要知道数字的最高位是多少位,所以最好将链表包装一下来保存最高位离小数点的位置。设计出的链表如下:
public class DataNode {
private int value;
public DataNode next;
public DataNode prep;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public DataNode getNext() {
return next;
}
public void setNext(DataNode next) {
this.next = next;
}
public DataNode getPrep() {
return prep;
}
public void setPrep(DataNode prep) {
this.prep = prep;
}
public DataNode(int value, DataNode next, DataNode prep) {
this.value = value;
this.next = next;
this.prep = prep;
}
}
public class BigData implements Comparable<BigData> {
private DataNode node;
//记录最高位
private int heigh;
//记录小数点位数
private int radixPoint;
//记录链表长度
private int length;
public BigData add(BigData data) {
return null;
}
public BigData minus(BigData data) {
return null;
}
public BigData multiply(BigData data) {
return null;
}
public BigData divide(BigData data) {
return null;
}
@Override
public int compareTo(BigData o) {
return 0;
}
}
这是定义好的数据的集合以及加减乘除运算,下一章我们就具体实现这四个运算,并阅读Java的BigDecimal,看官方对于大数的实现方式。