Sunday, January 30, 2022

Decimal to any base

package jan19;

import java.util.Scanner;

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

// Create a Scanner object for input
// Time Complexity: O(1), Space Complexity: O(1)
Scanner sc = new Scanner(System.in);

// Read the number from user
// Time Complexity: O(1)
int num = sc.nextInt();

// Read the base from user
// Time Complexity: O(1)
int base = sc.nextInt();

}

// Case Time Complexity Space Complexity
// Best Case O(logbasen) O(1)
// Average Case O(logbasen) O(1)
// Worst Case O(logbasen) O(1)
public void method1(int num, int base) {
// Initialize answer
// Time Complexity: O(1), Space Complexity: O(1)
int ans = 0;

// Initialize position counter
// Time Complexity: O(1), Space Complexity: O(1)
int i = 0;

// Loop until number becomes 0
// Time Complexity: O(logbasen)
// because in every iteration, 'num' reduces by a factor of 'base'.
while (num > 0) {

// Find remainder when divided by base
// Time Complexity: O(1)
int remainder = num % base;

// Find quotient after division by base
// Time Complexity: O(1)
int divisor = num / base;

// Update the answer
// Time Complexity: O(log log n) (for Math.pow, very small and almost constant)
ans += (int) Math.pow(10, i++) * remainder;

// Update num to be divisor
// Time Complexity: O(1)
num = divisor;
}

// Print the final answer
// Time Complexity: O(1)
System.out.println(ans);
}

// Case Time Complexity Space Complexity
// Best Case O(logbasen) O(1)
// Average Case O(logbasen) O(1)
// Worst Case O(logbasen) O(1)
// Same big O, but much faster in practice.
public void method2(int num, int base) {
int ans = 0; // O(1)
int multiplier = 1; // Instead of using Math.pow()

while (num > 0) { // O(logbasen)
int remainder = num % base; // O(1)
ans += remainder * multiplier; // O(1)
num = num / base; // O(1)
multiplier *= 10; // O(1) -> simply multiplying by 10 each time
}

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

/*
Why is multiplier *= 10 better than Math.pow(10, i++)?
Because:
*** multiplier *= 10 ➔ simple integer multiplication → very fast (O(1))
*** Math.pow() ➔ uses internal floating point operations → slower, even if small.
*/


}








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