Given a positive integer N
, return the number of positive integers less than or equal to N
that have at least 1 repeated digit.
Example 1:
Input: 20 Output: 1 Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100 Output: 10 Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000 Output: 262
Note:
1 <= N <= 10^9
给定正整数 N
,返回小于等于 N
且具有至少 1 位重复数字的正整数。
示例 1:
输入:20 输出:1 解释:具有至少 1 位重复数字的正数(<= 20)只有 11 。
示例 2:
输入:100 输出:10 解释:具有至少 1 位重复数字的正数(<= 100)有 11,22,33,44,55,66,77,88,99 和 100 。
示例 3:
输入:1000 输出:262
提示:
1 <= N <= 10^9
Time Limit Exceeded
1 class Solution { 2 var N:Int = 0 3 func numDupDigitsAtMostN(_ N: Int) -> Int { 4 self.N = N; 5 return N + 1 - count(0, 0) 6 7 } 8 9 func count(_ mask:Int,_ num:Int) -> Int 10 { 11 if num > self.N {return 0} 12 var ret:Int = 1 13 var nd:Int = num == 0 ? 1 : 0 14 while(nd < 10) 15 { 16 if ((mask>>nd) & 1) == 0 17 { 18 ret += count(mask|(1<<nd), num*10+nd) 19 } 20 nd += 1 21 } 22 return ret 23 } 24 }
Time Limit Exceeded
1 class Solution { 2 var N:Int = 0 3 func numDupDigitsAtMostN(_ N: Int) -> Int { 4 var ret:Int = 0 5 for i in 1..<10 6 { 7 ret += count(N, (1 << i), i) 8 } 9 return (N - ret) 10 } 11 12 func count(_ limit:Int,_ mask:Int,_ num:Int) -> Int 13 { 14 if num > limit {return 0} 15 var ret:Int = 1 16 for i in 0..<10 17 { 18 if ((mask >> i) & 1) != 0{continue} 19 ret += count(limit, mask | (1 << i), num * 10 + i) 20 } 21 return ret 22 } 23 }