Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
Example:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99]
)
给定一个非负整数n,统计[0,10n)之间仅含不同数字的数。
分析:
给定n,求[0,10n)范围内各位均不相同的数的个数,可分别求出[0,101),[101,102),……,[10n-1,10n)各区间内符合条件的数的个数,再相加即为所求。
求第k个区间[10k-1,10k)内包含不同数字的数,即求所有k位数中符合条件的数。可通过排列组合来求得。第1位可取1~9共9种;第2位可取0~9,除去第1位所取的数字,共9种;第3位可取0~9,除去第1、第2位所取数字,共8种,……,第k位可取0~9,除去第1~k-1位所取数字,共(10-(k-1))=11-k种,记为f(k),即f(k)=11-k。
所以所求结果即为f(1)+f(2)+...+f(k)。
注意:1)当n=0时,取值范围为[0,1),0符合条件,即f(0)=1。2)n>10时,11位以上的数必含有相同数字,因此,f(k)=0(k>10)。
代码如下:
int countNumbersWithUniqueDigits(int n)
{if (n <= 0) return 1;if (n == 1) return 10;int rst = 10, cnt = 2, coef = 9;int maxCnt = n > 10 ? 10 : n;while (cnt <= maxCnt){coef *= (11 - cnt);rst += coef;cnt++;}return rst;
}