Skip to content

Commit 0447095

Browse files
committed
#2283: Check if Number Has Equal Digit Count and Digit Value; solution & tests.
1 parent cb14d91 commit 0447095

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* 2283
3+
* Check if Number Has Equal Digit Count and Digit Value
4+
**
5+
* You are given a 0-indexed string num of length n consisting of digits.
6+
*
7+
* Return true if for every index i in the range 0 <= i < n,
8+
* the digit i occurs num[i] times in num, otherwise return false.
9+
*
10+
* Example 1:
11+
* Input: num = "1210"
12+
* Output: true
13+
* Explanation:
14+
* num[0] = '1'. The digit 0 occurs once in num.
15+
* num[1] = '2'. The digit 1 occurs twice in num.
16+
* num[2] = '1'. The digit 2 occurs once in num.
17+
* num[3] = '0'. The digit 3 occurs zero times in num.
18+
* The condition holds true for every index in "1210", so return true.
19+
*
20+
* Example 2:
21+
* Input: num = "030"
22+
* Output: false
23+
* Explanation:
24+
* num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num.
25+
* num[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num.
26+
* num[2] = '0'. The digit 2 occurs zero times in num.
27+
* The indices 0 and 1 both violate the condition, so return false.
28+
*
29+
* Constraints:
30+
* • n == num.length
31+
* • 1 <= n <= 10
32+
* • num consists of digits.
33+
*
34+
* Hint 1:
35+
* Count the frequency of each digit in num.
36+
**
37+
* https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value/
38+
***/
39+
40+
namespace Problems;
41+
42+
public class CheckIfNumberHasEqualDigitCountAndDigitValue
43+
{
44+
public bool DigitCount( string num )
45+
{
46+
int[] countMap = new int[10];
47+
48+
foreach ( char c in num )
49+
{
50+
countMap[c - '0']++;
51+
}
52+
53+
for ( int i = 0; i < num.Length; i++ )
54+
{
55+
if ( countMap[i] != num[i] - '0' )
56+
{
57+
return false;
58+
}
59+
}
60+
61+
return true;
62+
}
63+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
using NUnit.Framework;
2+
3+
using Problems;
4+
5+
public class CheckIfNumberHasEqualDigitCountAndDigitValueTests
6+
{
7+
[TestCase( "1210", ExpectedResult = true )]
8+
[TestCase( "030", ExpectedResult = false )]
9+
public bool DigitCountTest( string num ) =>
10+
new CheckIfNumberHasEqualDigitCountAndDigitValue().DigitCount( num );
11+
}

0 commit comments

Comments
 (0)