当前位置:网站首页>【剑指 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;
}
};
边栏推荐
- 手机注册股票开户安全吗 开户需要钱吗
- How to use AAB to APK and APK to AAB of Google play apps on the shelves
- 记一次jar包冲突解决过程
- Slam learning notes - build a complete gazebo multi machine simulation slam from scratch (I)
- 面试之 top k问题
- "Everyday Mathematics" serial 56: February 25
- 线程池执行定时任务
- PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
- Netease UI automation test exploration: airtest+poco
- 8 cool visual charts to quickly write the visual analysis report that the boss likes to see
猜你喜欢

Add color to the interface automation test framework and realize the enterprise wechat test report

探索Cassandra的去中心化分布式架构

为抵制 7-Zip,列出 “三宗罪” ?网友:“第3个才是重点吧?”

Mysql 将逗号隔开的属性字段数据由列转行

Multithread 02 thread join

2022爱分析· 国央企数字化厂商全景报告

Low level version of drawing interface (explain each step in detail)

From "zero sum game" to "positive sum game", PAAS triggered the third wave of cloud computing

NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线

Explore Cassandra's decentralized distributed architecture
随机推荐
Pointcut expression
斑馬識別成狗,AI犯錯的原因被斯坦福找到了
First knowledge of database
程序猿如何快速成长
Colab works with Google cloud disk
Multithread 02 thread join
Learn from me about the enterprise flutter project: simplified framework demo reference
Thinking about telecommuting under the background of normalization of epidemic | community essay solicitation
Initial test of scikit learn Library
How to set up SVN server on this machine
Uploads labs range (with source code analysis) (under update)
手机注册股票开户安全吗 开户需要钱吗
记一次jar包冲突解决过程
如何在本机搭建SVN服务器
Qt插件之自定义插件构建和使用
"Everyday Mathematics" serial 56: February 25
Effect of ARP package on FTP dump under vxworks-6.6 system
8 cool visual charts to quickly write the visual analysis report that the boss likes to see
TCP擁塞控制詳解 | 3. 設計空間
一台服务器最大并发 tcp 连接数多少?65535?