LeetCode357
来源:互联网 发布:适合腐女用的软件 编辑:程序博客网 时间:2024/06/05 09:40
LeetCode 357
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])Credits:
Special thanks to @memoryless for adding this problem and creating all test cases.
Solution:
题意是返回0~10的n次方间,每个位数上的数字都不相同的数的总数。
根据不同的总位数n进行分析,num为位数为n时符合条件的数的总数。
n = 0时,num = 1;
n = 1时,num = 9;
n = 2时,num = 9*9;
n = 3时,num = 9*9*8;
….
n = 10时,num = 9*9*8*7*6*5*4*3*2*1;
hint:第一位有9个选择(除了0),第二位还剩9个选择(包括了0),第三位还有8个选择……
最后的返回值为所有可能的n的取值对应的num之和
class Solution {public: int countNumbersWithUniqueDigits(int n) { if(n == 0) return 1; if(n > 10) n = 10; int result = 1; for(int i = 1; i <= n; i++) result += getNum(i); return result; } int getNum(int n) { if(n == 0) { return 1; } else if(n == 1) { return 9; } else { int result = 9; for(int i = 0; i < n-1; i++) result = result*(9-i); return result; } }};
阅读全文
0 0
- LeetCode357
- LeetCode357. Count Numbers with Unique Digits
- leetcode357. Count Numbers with Unique Digits
- Leetcode357: Count Numbers with Unique Digits
- leetcode357: Count Numbers with Unique Digits
- LeetCode357. Count Numbers with Unique Digits题解
- 进程通信方式
- 你最不想错过的 2017 早期 25 个 Android 开源库
- ubuntu下分区工具
- dfs玄学剪枝法集锦
- 第四章作业
- LeetCode357
- 图像特征概念
- Activiti工作流框架学习(一)——环境的搭建和数据表的了解
- 【单链表经典面试题解析三】在无头单链表的一个非头节点前插入一个节点(要求不能遍历单链表)
- 网页电子简历模板
- 数据分割算法:输入一个数计算出其位数,并打印出每一位的数
- Java消息服务____ActiveMQ_RabbitMQ_Kafka介绍
- IMX6Q 触摸屏调试(TSC2007驱动)
- Android导入第三方SDK时 Execution failed for task ':app:transformClassesWithJarMergingForDebu ‘ 错误的解决方法