1281. 整数的各位积和之差

诸神缄默不语-个人CSDN博文目录
力扣刷题笔记


文章目录

  • [1. 简单粗暴的遍历](#1. 简单粗暴的遍历)
  • [2. 其实也是遍历,但是用Python内置函数只用写一行](#2. 其实也是遍历,但是用Python内置函数只用写一行)

1. 简单粗暴的遍历

Python版:

python 复制代码
class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        he=0
        ji=1
        while n>=1:
            last_number=n%10
            he+=last_number
            ji*=last_number
            n=n//10  #就是n=int(n/10)的意思
        return ji-he

Java版:

java 复制代码
class Solution {
    public int subtractProductAndSum(int n) {
        int he=0;
        int ji=1;
        while(n>=1){
            int last_number=n%10;
            he+=last_number;
            ji*=last_number;
            n/=10;  //我一开始写成了n=(int)(n/10);  Java的话不需要做这个转换
        }
        return ji-he;
    }
}

时间复杂度: O ( log ⁡ n ) O(\log n) O(logn)

空间复杂度: O ( 1 ) O(1) O(1)

参考ChatGPT的回答,解释一下时间复杂度:

这个函数的目的是计算给定数字 n n n 的各个数字的乘积与和的差值。在这个过程中,你会遍历整个数字的每一位。

时间复杂度是 O ( log ⁡ n ) O(\log n) O(logn) 的原因是你每次迭代都会通过 n = n / / 10 n = n // 10 n=n//10 将数字的位数减少一位。因此,你将执行与数字 n n n 的位数相同的迭代次数。

现在,让我们理解为什么数字 n n n 最多有 log ⁡ n \log n logn 位。

给定一个 k k k 位的数字 n n n,最大值为 1 0 k − 1 10^k-1 10k−1,最小值为 1 0 k − 1 10^{k-1} 10k−1:

1 0 k − 1 ≤ n < 1 0 k 10^{k-1} \leq n < 10^k 10k−1≤n<10k

取两边的对数,你得到:

k − 1 ≤ log ⁡ 10 n < k k-1 \leq \log_{10} n < k k−1≤log10n<k

所以 k k k就是数字 n n n 的位数,它的上界是 log ⁡ 10 n + 1 \log_{10} n+1 log10n+1。

因此,遍历数字 n n n 的每一位需要 O ( log ⁡ n ) O(\log n) O(logn) 的时间。

2. 其实也是遍历,但是用Python内置函数只用写一行

python 复制代码
class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        return eval('*'.join(str(n))) - eval('+'.join(str(n)))
相关推荐
嗯嗯=1 天前
python学习篇
开发语言·python·学习
WoY20201 天前
opencv-python在ubuntu系统中缺少依赖
python·opencv·ubuntu
大游小游之老游1 天前
Python中如何实现一个程序运行时,调用另一文件中的函数
python
全靠bug跑1 天前
Spring Cache 实战:核心注解详解与缓存过期时间配置
java·redis·springcache
mantch1 天前
个人 LLM 接口服务项目:一个简洁的 AI 入口
人工智能·python·llm
Swift社区1 天前
LeetCode 465 最优账单平衡
算法·leetcode·职场和发展
聆风吟º1 天前
【数据结构手札】空间复杂度详解:概念 | 习题
java·数据结构·算法
weixin_445054721 天前
力扣热题51
c++·python·算法·leetcode
计算机程序设计小李同学1 天前
基于SpringBoot的个性化穿搭推荐及交流平台
java·spring boot·后端
是一个Bug1 天前
50道核心JVM面试题
java·开发语言·面试