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;
      }
};

你可能感兴趣的:(c++)