当前位置:网站首页>剑指Offer 64.求1+2+...+n 递归+&&
剑指Offer 64.求1+2+...+n 递归+&&
2022-08-02 03:33:00 【HotRabbit.】
题目
求 1+2+…+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
示例 1:
输入: n = 3
输出: 6
示例 2:
输入: n = 9
输出: 45
限制:
1 <= n <= 10000
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/qiu-12n-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
这道题没啥思路 直接看题解了
题解
递归:
巧妙的用&&
来判断。
x != 0 && 1 / x > x + y ;
如果x等于0,那么第二部分的运算就不会计算。因此,如果x为0,也就不会出现1/x,除以0的错误也不会出现
class Solution {
public int sumNums(int n) {
boolean flag = n > 0 && (n += sumNums(n - 1)) > 0;
return n;
}
}
快速乘:
class Solution {
public int sumNums(int n) {
int ans = 0, A = n, B = n + 1;
boolean flag;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
flag = ((B & 1) > 0) && (ans += A) > 0;
A <<= 1;
B >>= 1;
return ans >> 1;
}
}
边栏推荐
猜你喜欢
随机推荐
2020 - AAAI - 图像修复 Image Inpainting论文导读 -《Region Normalization for Image Inpainting》
进程(番外):自定义shell命令行解释器
Process (in): process state, process address space
[Arduino connects the clock module to display the time on LCD1602]
【Arduino connects DHT11 humidity and temperature sensor】
模拟电子技术------半导体
install 命令
PCIE电路设计
Comparison between Boda Industrial Cloud and Alibaba Cloud
Lightly:新一代的C语言IDE
[DS3231 RTC real-time clock module and Arduino interface to build a digital clock]
【LeetCode】设计链表
本地数据库 sqlite3 编译和使用
振芯科技GM8285C:功能TTL转LVDS芯片简介
【面试必看】链表的常见笔试题
WebApp 在线编程成趋势:如何在 iPad、Matepad 上编程?
联阳IT6561|IT6561FN方案电路|替代IT6561方案设计DP转HDMI音视频转换器资料
与TI的lvds芯片兼容-GM8284DD,GM8285C,GM8913,GM8914,GM8905C,GM8906C,国腾振芯LVDS类芯片,
IDEA2021.2安装与配置(持续更新)
Comparative analysis of mobile cloud IoT pre-research and Alibaba Cloud development