当前位置:网站首页>【剑指 Offer 】64. 求1+2+…+n
【剑指 Offer 】64. 求1+2+…+n
2022-07-03 16:29:00 【LuZhouShiLi】
剑指 Offer 64. 求1+2+…+n
题目
求 1+2+…+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路
- 将if判断语句转换成短路求值的方法来做。
- 短路求值:if(A & &B) // 如果A是True, 那么就要继续看B,A是False,没有必要看B;if(A || B) // 如果A是True,那么没有必要看B,如果A是Flase,还是要看B。
- 先写出普通的递归形式,在改写成短路求值形式
代码
- 短路求值
class Solution {
public:
int sumNums(int n) {
bool x = n > 1 && (n += sumNums(n - 1)) > 0;
return n;
}
};
- 递归形式
class Solution {
public:
int sumNums(int n) {
if(n == 1) return 1;
n += sumNums(n - 1);
return n;
}
};
边栏推荐
- [proteus simulation] 74hc595+74ls154 drive display 16x16 dot matrix
- Cocos Creator 2. X automatic packaging (build + compile)
- TCP拥塞控制详解 | 3. 设计空间
- Slam learning notes - build a complete gazebo multi machine simulation slam from scratch (II)
- Why does the std:: string operation perform poorly- Why do std::string operations perform poorly?
- 一台服务器最大并发 tcp 连接数多少?65535?
- Develop team OKR in the way of "crowdfunding"
- Characteristic polynomial and constant coefficient homogeneous linear recurrence
- Netease UI automation test exploration: airtest+poco
- [combinatorics] combinatorial identities (sum of variable terms 3 combinatorial identities | sum of variable terms 4 combinatorial identities | binomial theorem + derivation to prove combinatorial ide
猜你喜欢
初试scikit-learn库
Threejs Part 2: vertex concept, geometry structure
Mysql 将逗号隔开的属性字段数据由列转行
为抵制 7-Zip,列出 “三宗罪” ?网友:“第3个才是重点吧?”
消息队列消息丢失和消息重复发送的处理策略
Le zèbre a été identifié comme un chien, et la cause de l'erreur d'AI a été trouvée par Stanford
跟我学企业级flutter项目:简化框架demo参考
【声明】关于检索SogK1997而找到诸多网页爬虫结果这件事
线程池执行定时任务
NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线
随机推荐
Threejs Part 2: vertex concept, geometry structure
[statement] about searching sogk1997 and finding many web crawler results
PHP CI(CodeIgniter)log级别设置
[proteus simulation] 74hc595+74ls154 drive display 16x16 dot matrix
Explore Netease's large-scale automated testing solutions see here see here
Google Earth engine (GEE) - daymet v4: daily surface weather data set (1000m resolution) including data acquisition methods for each day
相同切入点的抽取
香港理工大学|数据高效的强化学习和网络流量动态的自适应最优周界控制
Low level version of drawing interface (explain each step in detail)
[redis foundation] understand redis master-slave architecture, sentinel mode and cluster together (Demo detailed explanation)
PHP中register_globals参数设置
Explore Cassandra's decentralized distributed architecture
TCP擁塞控制詳解 | 3. 設計空間
Thinking about telecommuting under the background of normalization of epidemic | community essay solicitation
【LeetCode】94. Middle order traversal of binary tree
(补)双指针专题
[combinatorics] combinatorial identities (sum of variable terms 3 combinatorial identities | sum of variable terms 4 combinatorial identities | binomial theorem + derivation to prove combinatorial ide
From the 18th line to the first line, the new story of the network security industry
Mixlab编辑团队招募队友啦~~
Visual SLAM algorithms: a survey from 2010 to 2016