剑指offer——面试题32:从1到n整数中1出现的次数
来源:互联网 发布:网络规划设计师教材 编辑:程序博客网 时间:2024/05/16 16:05
int NumberOf1Between1AndN_Solution1(unsigned int n){ int number = 0; for(unsigned int i = 1; i <= n; ++ i) number += NumberOf1(i); return number;}int NumberOf1(unsigned int n){ int number = 0; while(n) { if(n % 10 == 1) number ++; n = n / 10; } return number;}
int NumberOf1Between1AndN_Solution2(int n){ if(n <= 0) return 0; char strN[50]; sprintf(strN, "%d", n); return NumberOf1(strN);}int NumberOf1(const char* strN){ if(!strN || *strN < '0' || *strN > '9' || *strN == '\0') return 0; int first = *strN - '0'; unsigned int length = static_cast<unsigned int>(strlen(strN)); if(length == 1 && first == 0) return 0; if(length == 1 && first > 0) return 1; // 假设strN是"21345" // numFirstDigit是数字10000-19999的第一个位中1的数目 int numFirstDigit = 0; if(first > 1) numFirstDigit = PowerBase10(length - 1); else if(first == 1) numFirstDigit = atoi(strN + 1) + 1; // numOtherDigits是01346-21345除了第一位之外的数位中1的数目 int numOtherDigits = first * (length - 1) * PowerBase10(length - 2); // numRecursive是1-1345中1的数目 int numRecursive = NumberOf1(strN + 1); return numFirstDigit + numOtherDigits + numRecursive;}int PowerBase10(unsigned int n){ int result = 1; for(unsigned int i = 0; i < n; ++ i) result *= 10; return result;}
0 0
- 剑指offer 面试题32—从1到n整数中1出现的次数
- [剑指offer][面试题32]从1到n整数中1出现的次数
- 剑指Offer:面试题32 从1到n整数中1出现的次数
- 剑指offer-面试题32:从1到n整数中1出现的次数
- 算法 剑指Offer 面试题32 从1到n整数中1出现的次数
- 剑指Offer----面试题32:从1到n整数中1出现的次数
- 剑指offer面试题 32:从 1 到 n 整数中 1 出现的次数
- 剑指offer面试题32:从1到n整数中1出现的次数
- 【剑指offer】面试题32-从1到n整数中1出现的次数
- 剑指Offer系列-面试题32:从1到n整数中1出现的次数
- 剑指offer 面试题32 从 1 到 n 整数中 1 出现的次数
- 剑指offer-面试题32-从1到n整数中1出现的次数
- 剑指offer面试题[32]:从1到n整数中1出现的次数
- 【剑指Offer】面试题32:从1到n整数中1出现的次数
- 剑指Offer:面试题32:从1到n整数中1出现的次数
- 【剑指offer】5.2时间效率——面试题32:从1到n整数中1出现的次数
- 剑指Offer:面试题32——从1到n整数中1出现的次数(java实现)
- 剑指Offer:面试题32——从1到n整数中1出现的次数(java实现)
- gexf
- Hadoop之MapReduce快速入门
- Android TabLayout使用以及自定义TabLayout的item
- JAVA从数据库中拿到数据
- 电子招投标中的时间节点汇总
- 剑指offer——面试题32:从1到n整数中1出现的次数
- Cohort Analysis组群分析(1)
- 欢迎使用CSDN-markdown编辑器
- Xcode项目引入外部文件夹,不能引用问题
- Java中如何使用嵌入MySQL
- android中跨进程通讯的4种方式
- 即将25,人生路都走了三分之一。赶紧停一下,想想再战斗。
- angularJs 取<input type='file'>中文件名
- Python格式化输出