网站开发时ie11的兼容,html购物网页设计,可以货代从哪些网站开发客户,37网游【LetMeFly】1281.整数的各位积和之差
力扣题目链接#xff1a;https://leetcode.cn/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
给你一个整数 n#xff0c;请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。 示例 1#xff1a;
…【LetMeFly】1281.整数的各位积和之差
力扣题目链接https://leetcode.cn/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
给你一个整数 n请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。 示例 1
输入n 234
输出15
解释
各位数之积 2 * 3 * 4 24
各位数之和 2 3 4 9
结果 24 - 9 15示例 2
输入n 4421
输出21
解释
各位数之积 4 * 4 * 2 * 1 32
各位数之和 4 4 2 1 11
结果 32 - 11 21提示
1 n 10^5
方法一取出每一位
这道题主要在考察如何取出一个整数的每一位。当然可以使用内置函数将整数转为字符串再遍历字符串的每一位。但是还可以
在整数 n n n不为零时
取出 n % 10 n \% 10 n%10来做运算 n / 10 n / 10 n/10
这样就取出整数的每一位了。
时间复杂度 O ( log 10 n ) O(\log_{10}n) O(log10n)空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C
class Solution {
public:int subtractProductAndSum(int n) {int mul 1, cnt 0;while (n) {mul * n % 10;cnt n % 10;n / 10;}return mul - cnt;}
};Python
class Solution:def subtractProductAndSum(self, n: int) - int:mul, cnt 1, 0while n:mul * n % 10cnt n % 10n // 10return mul - cnt同步发文于CSDN原创不易转载请附上原文链接哦~ Tisfyhttps://letmefly.blog.csdn.net/article/details/132179859