Sum of 2 numbers, represented with linked lists, where digits are in backward order or forward order.
Backward order Example
- INPUT:(7->1->6) + (5->9->2) = 617+295
- OUTPUT: 2->1->9 = 912
Forward order Example
- INPUT:(7->1->6) + (5->9->2) = 716+592
- OUTPUT: 1>-3->0->8 = 1308
I'm starting with this method. I'm giving it list and size and I'm extrapolating each digit with base 10 notation. Time complexity should be O(n) for each list, and Space complexity should be O(1). Am I right?
public static int getNumber(LinkedList<Integer> num_list,int size){
int number= 0;
int pow = 0;//size-1 if it's in forward order
for (int d: num_list){
number += d * Math.pow(10.0, pow);
pow++;//pow-- if it's in forward order
}
return number;
}
Main
LinkedList<Integer> num1 = new LinkedList<>();
LinkedList<Integer> num2 = new LinkedList<>();
int sum,temp;
int count_digit = 0;
num1.add(7);
num1.add(1);
num1.add(6);
num2.add(5);
num2.add(9);
num2.add(2);
sum = getNumber(num1,num1.size()) + getNumber(num2,num2.size());
temp = sum;
//Counting the number of digits
while(temp!=0){
temp /= 10;
count_digit++;
}
LinkedList<Integer> result = new LinkedList<>();
Backward Solution
In that case, Space complexity should be O(1) and time O(n). Right?
for (int i = 0; i < count_digit;i++){
temp = sum % 10;
sum/= 10;
result.add(temp);
}
for(int d: result)
System.out.print(d);//Print node
System.out.println();
System.out.println(getNumber(result, result.size())); //print result
Frontward Solution
I didn't find any way to not implement another Structure. In that case, I changed getNumber method, using commented code.
int[] digit = new int[count_digit];
for(int i = digit.length-1; i >= 0; i--){
temp = sum % 10;
digit[i]= temp;
sum/= 10;
}
for(int d: digit){
System.out.print(d);
result.add(d);
}
//Just checking
System.out.println();
for (int d: result)
System.out.println(d);
At the end time complexity should be O(3n) (first list+ second list + array population) and, if I'm right, it should be considered like O(n). Space complexity should be O(n). There is a way to reduce space complexity?
List
as output, there's no trace of it in your code, if the output was just a number , there wouldn't need to specify the list. \$\endgroup\$