Saturday, May 24, 2025

Any base addition

  1. You are given a base b

2. You are given 2 numbers of base b

3. You are required to add two numbers and print their values in base b.


Input Format:

- A base b

- A number n1

- A number n2


Output:

sum of n1 & n2 in base b


Constraints:

2 <= b <= 10

0 <= n1 <= 256

0 <= n2 <= 256



package jan19;

public class AnyBaseAddition {
public static void main(String[] args) {
int n1_b_8 = 236;
int n2_b_8 = 754;
int base = 8;

sum(n1_b_8, n2_b_8, base);
}

/**
* Adds two numbers given in a specific base and prints the result in that base.
*
* Time Complexity: O(max(d1, d2))
* - Where d1 and d2 are the number of digits in n1 and n2.
* - In each iteration, one digit from each number is processed.
*
* Space Complexity: O(1)
* - Uses a fixed amount of space regardless of input size.
*/
private static void sum(int n1B8, int n2B8, int base) {
int carry = 0, ans = 0, power = 0;

while (n1B8 > 0 || n2B8 > 0 || carry > 0) {
int a = n1B8 % 10;
int b = n2B8 % 10;
n1B8 = n1B8 / 10;
n2B8 = n2B8 / 10;

int sum = a + b + carry;
carry = sum / base;

ans += (sum % base) * (int) Math.pow(10, power++);
}

System.out.println(ans);
}
}


CaseTime ComplexitySpace ComplexityExplanation
Best CaseO(1)O(1)When both numbers are 0, only one loop iteration runs.
Average CaseO(d)O(1)Where d is the number of digits in the longer of the two numbers.
Worst CaseO(d)O(1)Carries continue through all digits, requiring processing every digit. 

💡 Note: The number of digits d in a number n is O(log₁₀(n)), so technically it's O(log₁₀(n)), but in competitive programming and base conversion contexts, we usually denote it as O(d) to reflect digit-based iterations.

 

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...