Leetcode 2729. Check if The Number is Fascinating
2729. Check if The Number is Fascinating
You are given an integer n and a fascinating number is a number such that when it is multiplied by 1, 2, and 3, and the results are concatenated together in order, all the digits from 1 to 9 are present exactly once.
For example:
192 is a fascinating number because 192 * 1 = 192, 192 * 2 = 384, and 192 * 3 = 576, and 192384576 contains all the digits from 1 to 9 exactly once.100 is not a fascinating number as the concatenation 100200300 contains multiple zeros and doesn’t contain some other digits.Given an integer n, return true if it is a fascinating number, or false otherwise.
n?
1 <= n <= 10^4 but this needs to be confirmed.true/false as a boolean?
Generate and Concatenate: Calculate n * 1, n * 2, and n * 3. Concatenate these results into a single string.
Verify Digits: Ensure that the concatenated string contains exactly nine distinct digits without any repetition, and that these digits are exactly 1 through 9.
Immediate Validation: If the length of the concatenated string is not 9, return false immediately as it cannot be valid.
Hence, the overall time complexity is O(1), as the operations work on fixed-size data.
public class Solution {
public boolean isFascinating(int n) {
// Generate the concatenated string
String concatenated = "" + n + (n * 2) + (n * 3);
// If the length of concatenated string is not 9, it's not fascinating
if (concatenated.length() != 9) {
return false;
}
// We need every digit from 1 to 9 to appear exactly once
boolean[] digits = new boolean[10];
for (char ch : concatenated.toCharArray()) {
int digit = ch - '0';
// If the digit is 0 or already seen, return false
if(digit == 0 || digits[digit]) {
return false;
}
digits[digit] = true;
}
// Ensure all digits from 1 to 9 are seen exactly once
for (int i = 1; i <= 9; i++) {
if (!digits[i]) {
return false;
}
}
return true;
}
}
You can use this code to determine if a given number n is a fascinating number by calling isFascinating(n) with the desired integer value. The solution ensures precise verification in constant time.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?