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(log₍base₎n) O(1)
// Average Case O(log₍base₎n) O(1)
// Worst Case O(log₍base₎n) 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(log₍base₎n)
// 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(log₍base₎n) O(1)
// Average Case O(log₍base₎n) O(1)
// Worst Case O(log₍base₎n) 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(log₍base₎n)
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.
*/
}
Sunday, January 30, 2022
Decimal to any base
Subscribe to:
Post Comments (Atom)
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:...
-
https://leetcode.com/problems/reverse-integer/description/ Integer.MAX_VALUE = 2,147,483,647 = 2 31 - 1 Integer.MIN_VALUE = -2,147,483,64...
-
https://leetcode.com/problems/two-sum/description/ Given the constraints: 2 <= nums.length <= 10⁴ -10⁹ <= nums[i] <= 10⁹ -10...
-
For this particular question, we only have the In - region. So, the code looks like : package pep.Day7 ; public class TowerOfHanoi { p...


No comments:
Post a Comment