package jan18;
import java.util.Scanner;
public class rotateNumber {
/*
* Time Complexity (TC):
*
* Best case: O(1)
* - When n = 0 or a single-digit number, the length calculation takes constant time.
*
* Average case: O(1)
* - The time is primarily spent on finding the number of digits in n.
*
* Worst case: O(1)
* - The time complexity remains O(1) since we calculate the length for any input number.
*
* Space Complexity (SC):
*
* SC: O(1)
* - The space used is constant; we only use a few integer variables (n, k, length)
* and do not require extra storage.
*/
public static void main(String[] args) {
// Input: reading two integers n and k
// Time Complexity: O(1) for input
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // The number to rotate
int k = scanner.nextInt(); // Number of rotations
// Calculating the length (number of digits) of the number n
// Time Complexity: O(log10(n)) = O(1)
int length = (int) Math.log10(n) + 1;
// If k is negative, convert it to equivalent positive rotation
// Time Complexity: O(1)
if (k < 0)
k = length + k;
// Reduce k to within the range of [0, length] using modulus
// Time Complexity: O(1)
k = k % length;
// Rotate the number
// Time Complexity: O(1) for the calculations
n = (n % (int) Math.pow(10, k) * (int) Math.pow(10, length - k))
+ (n / (int) Math.pow(10, k));
// Output the rotated number
// Time Complexity: O(1) for printing
System.out.println(n);
}
}
Saturday, January 29, 2022
Rotate A Number
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