2283. Check if Number Has Equal Digit Count and Digit Value Easy
1/**
2 * [2283] Check if Number Has Equal Digit Count and Digit Value
3 *
4 * You are given a 0-indexed string num of length n consisting of digits.
5 * Return true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num, otherwise return false.
6 *
7 * Example 1:
8 *
9 * Input: num = "1210"
10 * Output: true
11 * Explanation:
12 * num[0] = '1'. The digit 0 occurs once in num.
13 * num[1] = '2'. The digit 1 occurs twice in num.
14 * num[2] = '1'. The digit 2 occurs once in num.
15 * num[3] = '0'. The digit 3 occurs zero times in num.
16 * The condition holds true for every index in "1210", so return true.
17 *
18 * Example 2:
19 *
20 * Input: num = "030"
21 * Output: false
22 * Explanation:
23 * num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num.
24 * num[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num.
25 * num[2] = '0'. The digit 2 occurs zero times in num.
26 * The indices 0 and 1 both violate the condition, so return false.
27 *
28 *
29 * Constraints:
30 *
31 * n == num.length
32 * 1 <= n <= 10
33 * num consists of digits.
34 *
35 */
36pub struct Solution {}
37
38// problem: https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value/
39// discuss: https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value/discuss/?currentPage=1&orderBy=most_votes&query=
40
41// submission codes start here
42
43impl Solution {
44 pub fn digit_count(num: String) -> bool {
45 let mut d = vec![0; 10];
46 for c in num.chars() {
47 d[c as usize - '0' as usize] += 1;
48 }
49 for (i, c) in num.chars().enumerate() {
50 if c as i32 - '0' as i32 != d[i] {
51 return false;
52 }
53 }
54 true
55 }
56}
57
58// submission codes end
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63
64 #[test]
65 fn test_2283() {
66 assert!(Solution::digit_count("1210".to_owned()));
67 }
68}
69
Back
© 2025 bowen.ge All Rights Reserved.