// 面试题43:从1到n整数中1出现的次数 // 题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如 // 输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。 #include <cstdio> #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 > 0) { 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_s(strN, "%d", n); return NumberOf1(strN); } int NumberOf1(const char* strN) { if (!strN || *strN < '0' || *strN > '9' || *strN == '