Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created September 9, 2018 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/c27c5c878e0619a0b20eaaf7b5a5c27f to your computer and use it in GitHub Desktop.
Save jianminchen/c27c5c878e0619a0b20eaaf7b5a5c27f to your computer and use it in GitHub Desktop.
902 Numbers at most given digit set - wrote the code in the contest and first few hours after the content
public class Solution {
public int AtMostNGivenDigitSet(string[] sortedDigits, int N)
{
var number = AtMostNGivenDigitSetHelper(sortedDigits, N);
return number;
}
public static int AtMostNGivenDigitSetHelper(string[] sortedDigits, int N)
{
if (N <= 0)
return 0;
var smallerEqualOnes = findLessEqual(sortedDigits);
var smallerOnes = findLess(sortedDigits);
var hashset = new HashSet<int>();
foreach (var item in sortedDigits)
{
hashset.Add((int)(item[0] - '0'));
}
// base case
if (N < 10)
{
return smallerEqualOnes[N - 1];
}
var count = 0;
var chars = N.ToString();
var leftmostDigit = (chars[0] - '0');
var digits = sortedDigits.Length;
var length = chars.Length;
var numbers = smallerOnes[leftmostDigit - 1];
count += numbers * (int)Math.Pow(digits, length - 1);
if (hashset.Contains(leftmostDigit))
{
// 123 - >= 100 and < 123
count += AtMostNGivenDigitSetHelper(sortedDigits, Convert.ToInt32(chars.Substring(1)));
}
// < 100
for(int i = 0; i < length - 1; i++)
{
count += (int)Math.Pow(digits, i + 1);
}
return count;
}
private static int[] findLessEqual(string[] D)
{
var hashset = new HashSet<int>();
foreach (var item in D)
{
hashset.Add((int)(item[0] - '0'));
}
var numbers = new int[9]; // 0 - 8
int count = 0;
for (int i = 1; i <= 9; i++)
{
if (hashset.Contains(i))
count++;
numbers[i - 1] = count;
}
return numbers;
}
// 1 2 3
private static int[] findLess(string[] D)
{
var hashset = new HashSet<int>();
foreach (var item in D)
{
hashset.Add((int)(item[0] - '0'));
}
var numbers = new int[9]; // 0 - 8
int count = 0;
for (int i = 1; i <= 9; i++)
{
if (hashset.Contains(i - 1))
count++;
numbers[i - 1] = count;
}
return numbers;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment