zoukankan      html  css  js  c++  java
  • 357. 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])

    题目含义: 给定一个数字N 找出 0≤ x < 10n中各位数字都不相同的数的个数。

    方法一:这里n代表整数的位数,当n=1时因为只有一个数字,所以0-9都是答案.当n>=2时,最高位可以为1-9任意一个数字,之后各位可以选择的数字个数依次为9, 8, 7, 6...1,通项公式为f(k) = 9(第一位的可选数量,从1到9共9个) * 9(第二位的可选数量,0-9共10个数中抛去第一位使用了的) * 8(第三位的可选数量,0-9共10个数中抛去前两位使用了的)  * ... (9 - k + 2),

    那么我们就可以根据n的大小,把[1, n]区间位数通过通项公式算出来累加起来即可  

     1     public int countNumbersWithUniqueDigits(int n) {
     2 //   这里n代表整数的位数,当n=1时因为只有一个数字,所以0-9都是答案.当n>=2时,最高位可以为1-9任意一个数字,之后各位可以选择的数字个数依次为9, 8, 7, 6...1   二位数的满足题意的是81个,[10 - 99]这90个数字中去掉[11,22,33,44,55,66,77,88,99]这9个数字,还剩81个。
     3 //  通项公式为f(k) = 9 * 9 * 8 * ... (9 - k + 2),那么我们就可以根据n的大小,把[1, n]区间位数通过通项公式算出来累加起来即可        
     4         if(n==0) return 1;  
     5         if(n==1) return 10;  
     6         int val = 9, ans = 10;  
     7         for(int i = 2; i <= n; i++)  
     8         {  
     9             val *= (9-i+2);  
    10             ans += val;  
    11         }  
    12         return ans;
    13     }
  • 相关阅读:
    每日总结2021.9.14
    jar包下载mvn
    每日总结EL表达语言 JSTL标签
    每日学习总结之数据中台概述
    Server Tomcat v9.0 Server at localhost failed to start
    Server Tomcat v9.0 Server at localhost failed to start(2)
    链表 java
    MVC 中用JS跳转窗体Window.Location.href
    Oracle 关键字
    MVC 配置路由 反复走控制其中的action (int?)
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7694312.html
Copyright © 2011-2022 走看看