// 面试题43:从1到n整数中1出现的次数 // 题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如 // 输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。 #include <iostream> #include <cstring> #include <cstdlib> // ====================方法一==================== //逐个判断,时间复杂度为O(nlogn),不好 int NumberOf1(unsigned int n); 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 NumberOf1(const char* strN); int PowerBase10(unsigned int n); 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 == '