#8 Daily Problems -AddTwoHugeNumbers

Arun Pandian M
2 min readJul 26, 2020

Hi guys today is my 8th day of solving the one problem per day.

Problem:

You’re given 2 huge integers represented by linked lists. Each linked list element is a number from 0 to 9999 that represents a number with exactly 4 digits. The represented number might have leading zeros. Your task is to add up these huge integers and return the result in the same format.

Example

  • For a = [9876, 5432, 1999] and b = [1, 8001], the output should be
    addTwoHugeNumbers(a, b) = [9876, 5434, 0].
  • Explanation: 987654321999 + 18001 = 987654340000.
  • For a = [123, 4, 5] and b = [100, 100, 100], the output should be
    addTwoHugeNumbers(a, b) = [223, 104, 105].
  • Explanation: 12300040005 + 10001000100 = 22301040105.

Input/Output

  • [execution time limit] 3 seconds (java)
  • [input] linkedlist.integer a
  • The first number, without its leading zeros.
  • Guaranteed constraints:
    0 ≤ a size ≤ 104,
    0 ≤ element value ≤ 9999.
  • [input] linkedlist.integer b
  • The second number, without its leading zeros.
  • Guaranteed constraints:
    0 ≤ b size ≤ 104,
    0 ≤ element value ≤ 9999.
  • [output] linkedlist.integer
  • The result of adding a and b together, returned without leading zeros in the same format.

My solution:

// Singly-linked lists are already defined with this interface:// class ListNode<T> {//   ListNode(T x) {//     value = x;//   }//   T value;//   ListNode<T> next;// }//ListNode<Integer> addTwoHugeNumbers(ListNode<Integer> a, ListNode<Integer> b) {int i=0;BigInteger total=null;String firstNumber="", secondNumber="";while(a!=null){if(i==0){firstNumber=""+a.value;}else{firstNumber=firstNumber+""+String.format("%04d" , a.value);}a=a.next;i++;}i=0;while(b!=null){if(i==0){secondNumber=""+b.value;}else{secondNumber=secondNumber+""+String.format("%04d" , b.value);}b=b.next;i++;}i=0;total= new BigInteger(""+firstNumber).add(new BigInteger(""+secondNumber));ListNode<Integer> listNode= new ListNode(0);ListNode temp=null;while (total.signum() >0) {System.out.println(total.remainder(new BigInteger(""+10000)) );int remaindervalue = total.remainder(new BigInteger(""+10000)).intValue();if(i==0){listNode=new ListNode(remaindervalue);temp=listNode;}else{temp.next=new ListNode(remaindervalue);temp=temp.next;}total = total.divide(new BigInteger(""+10000));i++;}ListNode<Integer> prev=null,current = listNode, next;while(current!=null){next=current.next;current.next=prev;prev=current;current=next;}listNode = prev;return listNode;}

Please learn and let me learn something from you guys. Please give me some claps if you like otherwise leave some suggestion to improve myslef. Thanks and bye…

Happy coding!

Buy me a coffee?
If you like this article, you can buy me a coffee. Thanks!

--

--

Arun Pandian M

Senior Android developer at FundsIndia, A time investor to learn new things about Programming. Currently in a relationship with Green Bug(Android).