JZ-C-32

剑指offer第三十二题:从1到n整数中1出现的次数

  1 //============================================================================
  2 // Name        : JZ-C-32.cpp
  3 // Author      : Laughing_Lz
  4 // Version     :
  5 // Copyright   : All Right Reserved
  6 // Description : 从1到n整数中1出现的次数
  7 //============================================================================
  8 
  9 #include <iostream>
 10 #include <stdio.h>
 11 #include <string.h>
 12 #include <stdlib.h>
 13 using namespace std;
 14 
 15 // ====================方法一:未考虑时间效率,时间复杂度O(n*logn)====================
 16 int NumberOf1(unsigned int n);
 17 
 18 int NumberOf1Between1AndN_Solution1(unsigned int n) {
 19     int number = 0;
 20 
 21     for (unsigned int i = 1; i <= n; ++i)
 22         number += NumberOf1(i); //对每个数字都要做除法和求余运算
 23 
 24     return number;
 25 }
 26 
 27 int NumberOf1(unsigned int n) {
 28     int number = 0;
 29     while (n) {
 30         if (n % 10 == 1)
 31             number++;
 32 
 33         n = n / 10;
 34     }
 35 
 36     return number;
 37 }
 38 
 39 // ====================方法二:将数字分为两段,如21345分为从1到1345 和 1346到21345,时间复杂度O(logn)====================
 40 int NumberOf1(const char* strN);
 41 int PowerBase10(unsigned int n);
 42 
 43 int NumberOf1Between1AndN_Solution2(int n) {
 44     if (n <= 0)
 45         return 0;
 46 
 47     char strN[50];
 48     sprintf(strN, "%d", n); //把格式化的数据写入某个字符串,这里是将整数写入strN字符数组中
 49 
 50     return NumberOf1(strN);
 51 }
 52 
 53 int NumberOf1(const char* strN) {
 54     if (!strN || *strN < '0' || *strN > '9' || *strN == '