Advertisement
Guest User

Untitled

a guest
Jun 24th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. // Definition for singly-linked list:
  2. // class ListNode<T> {
  3. //   ListNode(T x) {
  4. //     value = x;
  5. //   }
  6. //   T value;
  7. //   ListNode<T> next;
  8. // }
  9. //
  10. ListNode<Integer> addTwoHugeNumbers(ListNode<Integer> a, ListNode<Integer> b) {
  11.     if (a.value.equals(0) && a.next == null) {
  12.         return b;
  13.     } else if (b.value.equals(0) && b.next == null) {
  14.         return a;
  15.     }
  16.    
  17.     String aAmount = "";
  18.     while (a != null) {
  19.         aAmount += padValue(a.value);
  20.         a = a.next;
  21.     }
  22.    
  23.     String bAmount = "";
  24.     while (b != null) {
  25.         bAmount += padValue(b.value);
  26.         b = b.next;
  27.     }
  28.    
  29.     BigInteger bigAmount = new BigInteger(aAmount).add(new BigInteger(bAmount));
  30.    
  31.     Stack<Integer> stack = new Stack<Integer>();
  32.     while (!bigAmount.mod(new BigInteger("10000")).equals(bigAmount)) {
  33.         int newValue = bigAmount.mod(new BigInteger("10000")).intValue();
  34.         stack.push(newValue);
  35.         bigAmount = bigAmount.divide(new BigInteger("10000"));
  36.     }
  37.    
  38.     ListNode<Integer> head = new ListNode<Integer>(0);
  39.     ListNode<Integer> current = head;
  40.    
  41.     while (!stack.empty()) {
  42.         int newValue = stack.pop();
  43.         ListNode<Integer> newNode = new ListNode<Integer>(newValue);
  44.         current.next = newNode;
  45.         current = newNode;
  46.     }
  47.    
  48.     head.value = bigAmount.mod(new BigInteger("10000")).intValue();
  49.    
  50.     return head;
  51. }
  52.  
  53. String padValue(int value) {
  54.     String result = "";
  55.     if (value > 999) {
  56.         result += String.valueOf(value);
  57.     } else if (value > 99) {
  58.         result += "0" + String.valueOf(value);
  59.     } else if (value > 9) {
  60.         result += "00" + String.valueOf(value);
  61.     } else {
  62.         result += "000" + String.valueOf(value);
  63.     }
  64.     return result;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement