Saturday, January 29, 2022

Reverse A Number

package jan18;

import java.util.Scanner;

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

// Input the number
// Time Complexity: O(1) for reading input
int n = new Scanner(System.in).nextInt();

// Call method to reverse and print the number
// Time Complexity: O(log10(n)) for reversing the digits
method1(n);
}

// Method to reverse and print the number
// Time Complexity (TC): O(log10(n)) in the worst case
// O(log10(n)) can be simplified to O(log n) in Big O notation
// - Best case (n = 0): O(1), no iteration
// - Average case: O(log10(n)), proportional to the number of digits
// - Worst case (largest n): O(log10(n)), processing all digits
// Space Complexity (SC): O(1), constant space usage, O(1), constant space usage because
// no additional data structures or variables are used apart from the input variable n.
private static void method1(int n) {

// Handle negative numbers
// Time Complexity: O(1)
if (n < 0) {
n = -n; // Convert negative number to positive
}

// Loop to reverse the digits
// Time Complexity: O(log10(n)) because the number of digits is proportional to log10(n)
while (n > 0) {
// Extract the last digit and print it
// Time Complexity: O(1) for modulo and printing
System.out.print(n % 10);

// Remove the last digit
// Time Complexity: O(1) for division
n = n / 10;
}

}
}


eg 1.
while (n > 1) {
    n = n / 2;
}

Here Each step halves n.

Total steps = log₂(n) → again O(log n)


eg 2.

while (n > 0) { System.out.print(n % 10); n = n / 10; }

(Specifically, log₁₀(n) — but we simplify to O(log n) in Big O notation.)

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