Sunday, January 30, 2022

Any Base To Any Base



public class anyBaseToAnyBase {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt(); // O(1) - Read input number
int sourceBase = sc.nextInt(); // O(1) - Read source base
int finalBase = sc.nextInt(); // O(1) - Read final base

int val = numToBase(num, sourceBase); // O(log_sourceBase n) - Convert to decimal
baseToNum(val, finalBase); // O(log_finalBase val) - Convert to final base

}

public static int numToBase(int num, int sourceBase) {
int ans = 0;
int idx = 0;
while (num > 0) { // O(log_sourceBase n) - Loop iterates based on number of digits in base-sourceBase
int rem = num % 10; // O(1) - Extract last digit (assuming base 10 input)
ans += (int) Math.pow(sourceBase, idx++) * rem; // O(1) - Calculate decimal equivalent (assuming constant-time Math.pow)
num /= 10; // O(1) - Remove last digit
}

return ans;
}

public static void baseToNum(int num, int finalBase) {
int ans = 0;
int idx = 0;
while (num > 0) { // O(log_finalBase val) - Loop iterates based on number of digits in base-finalBase
int rem = num % finalBase; // O(1) - Extract last digit (assuming base-finalBase)
ans += (int) Math.pow(10, idx++) * rem; // O(1) - Calculate final base equivalent (assuming constant-time Math.pow)
num /= finalBase; // O(1) - Remove last digit
}

System.out.println(ans);
}
}


Time Complexity:

The time complexity analysis is based on the number of iterations required in 
the two conversion loops. The number of iterations in each loop depends on the 
number of digits in the corresponding base. 

1. Best Case: O(log min(sourceBase, finalBase)) - When the input number has a small number of digits in both bases.
In the best case, both bases have a small number of digits, resulting in fewer iterations. 
2. Worst Case: O(log max(sourceBase, finalBase)) - When the input number has a large number of digits in either base.
In the worst case, one or both bases have a large number of digits, leading to more iterations.
3. Average Case: O(log avg(sourceBase, finalBase)) - Assuming a random distribution of input numbers and bases.
The average case time complexity is between the best and worst case, depending 
on the distribution of input numbers and bases.


Space Complexity:
All Cases: O(1) - The space complexity remains constant as the code uses a 
constant amount of additional space for variables regardless of the input size.



Overall:

  • The anyBaseToAnyBase class has a time complexity that is generally efficient, especially for smaller numbers and bases.
  • The space complexity remains constant, making it suitable for most use cases.

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