Count Numbers with Unique Digits

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])

 1 public class Solution {
 2     public int countNumbersWithUniqueDigits(int n) {
 3         
 4         if (n < 1) return 1;
 5         if (n == 1) return 10;  // 0 - 10
 6         int count = countNumbersWithUniqueDigits(n - 1); // 1 到 n-1 位数。
 7         int result = 9;  // there are 9 choices in the first number. 9 in the second number, 8 in the third, 7 in the fourth number.......
 8         for (int i = 0; i < n - 1; i++) {  // n位数
 9             result = result * (9 - i);
10         }
11         return count + result;
12     }
13 }

 

posted @ 2016-07-26 12:38  北叶青藤  阅读(172)  评论(0)    收藏  举报