Welcome to Subscribe On Youtube
3908. Valid Digit Number
Description
You are given an integer n and a digit x.
A number is considered valid if:
- It contains at least one occurrence of digit
x, and - It does not start with digit
x.
Return true if n is valid, otherwise return false.
Example 1:
Input: n = 101, x = 0
Output: true
Explanation:
The number contains digit 0 at index 1. It does not start with 0, so it satisfies both conditions. Thus, the answer is true.
Example 2:
Input: n = 232, x = 2
Output: false
Explanation:
The number starts with 2, which violates the condition. Thus, the answer is false.
Example 3:
Input: n = 5, x = 1
Output: false
Explanation:
The number does not contain digit 1. Thus, the answer is false.
Constraints:
0 <= n <= 1050 <= x <= 9
Solutions
Solution 1: Simulation
We use a boolean variable $\textit{hasX}$ to record whether the digit $x$ appears in $n$.
We repeatedly take the last digit of $n$ and compare it with $x$. If they are equal, we set $\textit{hasX}$ to $\texttt{true}$. At the same time, we divide $n$ by $10$ to remove the last digit. When $n$ is less than or equal to $9$, it means we have checked all the digits. At this point, if $\textit{hasX}$ is $\texttt{true}$ and $n$ is not equal to $x$, then $n$ is a valid number and we return $\texttt{true}$; otherwise, we return $\texttt{false}$.
The time complexity is $O(\log n)$, where $n$ is the input integer. The space complexity is $O(1)$.
-
class Solution { public boolean validDigit(int n, int x) { boolean hasX = false; while (n > 9) { hasX = hasX || (n % 10 == x); n /= 10; } return hasX && (n != x); } } -
class Solution { public: bool validDigit(int n, int x) { bool hasX = false; while (n > 9) { hasX = hasX || (n % 10 == x); n /= 10; } return hasX && (n != x); } }; -
class Solution: def validDigit(self, n: int, x: int) -> bool: has_x = False while n > 9: has_x = has_x or n % 10 == x n //= 10 return has_x and n != x -
func validDigit(n int, x int) bool { hasX := false for n > 9 { hasX = hasX || (n%10 == x) n /= 10 } return hasX && (n != x) } -
function validDigit(n: number, x: number): boolean { let hasX: boolean = false; while (n > 9) { hasX = hasX || n % 10 === x; n = Math.floor(n / 10); } return hasX && n !== x; } -
impl Solution { pub fn valid_digit(mut n: i32, x: i32) -> bool { let mut has_x = false; while n > 9 { has_x = has_x || (n % 10 == x); n /= 10; } has_x && (n != x) } }