Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Definition for singly-linked list:
- // class ListNode<T> {
- // ListNode(T x) {
- // value = x;
- // }
- // T value;
- // ListNode<T> next;
- // }
- //
- ListNode<Integer> addTwoHugeNumbers(ListNode<Integer> a, ListNode<Integer> b) {
- if (a.value.equals(0) && a.next == null) {
- return b;
- } else if (b.value.equals(0) && b.next == null) {
- return a;
- }
- String aAmount = "";
- while (a != null) {
- aAmount += padValue(a.value);
- a = a.next;
- }
- String bAmount = "";
- while (b != null) {
- bAmount += padValue(b.value);
- b = b.next;
- }
- BigInteger bigAmount = new BigInteger(aAmount).add(new BigInteger(bAmount));
- Stack<Integer> stack = new Stack<Integer>();
- while (!bigAmount.mod(new BigInteger("10000")).equals(bigAmount)) {
- int newValue = bigAmount.mod(new BigInteger("10000")).intValue();
- stack.push(newValue);
- bigAmount = bigAmount.divide(new BigInteger("10000"));
- }
- ListNode<Integer> head = new ListNode<Integer>(0);
- ListNode<Integer> current = head;
- while (!stack.empty()) {
- int newValue = stack.pop();
- ListNode<Integer> newNode = new ListNode<Integer>(newValue);
- current.next = newNode;
- current = newNode;
- }
- head.value = bigAmount.mod(new BigInteger("10000")).intValue();
- return head;
- }
- String padValue(int value) {
- String result = "";
- if (value > 999) {
- result += String.valueOf(value);
- } else if (value > 99) {
- result += "0" + String.valueOf(value);
- } else if (value > 9) {
- result += "00" + String.valueOf(value);
- } else {
- result += "000" + String.valueOf(value);
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement