乐趣区

关于c++:Leetcode专题233数字1的个数

力扣链接:
https://leetcode.cn/problems/…
解题思路:

  1. 找法则
    从个位数开始,依照以后位将数字分成右边 high 局部,左边 low 局部,以后位的数字分为三种类型:
    (1)0: res = high * digit;
    (2)1: res = high * digit + low + 1;
    (3)2/…/9: res = (high + 1) * digit;
class Solution{
  public:
      int countDigitOne(int n) {
          // 参数判断
          if (n < 1) {return 0;}
          // 从个位数开始
          long digit = 1;
          int high = n / 10, low = 0, cur = n % 10;
          int res = 0;
          while(cur != 0 || high != 0) {if (cur == 0) {res += high * digit;}
              else if (cur == 1) {res += high * digit + low + 1;}
              else {res += (high + 1) * digit;
              }
              low += cur * digit;
              high = high / 10;
              cur = high % 10;
              digit *= 10;
          }
          return res;
      }
};
退出移动版