Saturday, May 24, 2025

Any base substraction

1. You are given a base b

2. You are given 2 numbers n1 and n2 of base b

3. You are required to substract n1 from n2 and print the value


Input Format:

- A base b

- A number n1

- A number n2


Output:

diff of n2 & n1 in base b


Constraints:

2 <= b <= 10

0 <= n1 <= 256

0 <= n2 <= 256


package jan19;

public class AnyBaseSubstraction {
public static void main(String[] args) {

int n1b8 = 1212;
int n2b8 = 236;
int base = 8;

anyBaseSubstraction(n1b8, n2b8, base);
}

/**
* Time Complexity: O(d), where d = number of digits in the longer number
* Space Complexity: O(1), constant space used
*/
private static void anyBaseSubstraction(int n1b8, int n2b8, int base) {

int carryFromPrevious = 0, ans = 0, power = 0; // O(1)
while (n1b8 > 0 || n2b8 > 0) { // O(d) loop where d = number of digits

int a = n1b8 % 10; // O(1)
if (carryFromPrevious == -1)
a = a - 1; // O(1)
int b = n2b8 % 10; // O(1)

n1b8 = n1b8 / 10; // O(1)
n2b8 = n2b8 / 10; // O(1)

if (a < b) {
carryFromPrevious = -1; // O(1)
a = a + base; // O(1)
}

ans += (a - b) * (int) Math.pow(10, power++); // O(1), since power is small (integer)
}

System.out.println(ans); // O(1)
}
}


📊 Complexity Table

CaseTime ComplexitySpace ComplexityExplanation
BestO(1)O(1)If both numbers are zero or subtraction completes in one digit.
AverageO(d)O(1)Where d is the number of digits in the longer of the two numbers.
WorstO(d)O(1)When subtraction and borrow propagation continue for all digits.
💡 d is the number of digits, typically O(log₁₀(n)), but represented as O(d) to reflect per-digit operations in base conversions.

✅ Uses constant space as it stores only digits and a few integers, no extra data structures are used.

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:...