【Leetcode】1281. Subtract the Product and Sum of Digits of an Integer

题目地址:

https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/

给定一个正整数 n n n,求其各个位的乘积减去各个位的和。

代码如下:

class Solution {
 public:
  int subtractProductAndSum(int n) {
    int prod = 1, sum = 0;
    while (n > 0) {
      int x = n % 10;
      prod *= x;
      sum += x;
      n /= 10;
    }

    return prod - sum;
  }
};

时间复杂度 O ( log ⁡ n ) O(\log n) O(logn),空间 O ( 1 ) O(1) O(1)

你可能感兴趣的:(LC,二分,位运算与数学,leetcode,算法,c++)