Skip to content

Commit 4de35da

Browse files
committed
面试题64. 求1+2+…+n
1 parent d19335f commit 4de35da

File tree

1 file changed

+15
-0
lines changed
  • leetcode-cn/面试题64. 求1+2+…+n

1 file changed

+15
-0
lines changed

leetcode-cn/面试题64. 求1+2+…+n/README.md

+15
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,21 @@
2727

2828
## Solution 1.
2929

30+
思略: 计算 (n^2 + n) / 2
31+
32+
其中`n^2`没法简单地用位运算直接得到. 考虑`6 * 6`可以拆解为`6 * 4 + 6 * 2`, 也就是
33+
34+
数字 | 二进制 | 左移位数 | 结果
35+
---|---|---|---
36+
4 | 100 | 左移2位 | `110 << 2`
37+
2 | 10 | 左移1位 | `110 << 1`
38+
39+
所以, 规律就是如果`n`的第`i`位是`1`, 就将`n << i`加到结果中.
40+
41+
对于给定`i`, 我想到一种表达方式为`-((n >> i) & 1) & (n << i)`.
42+
43+
因为10000只有14bits, 所以`i`枚举从`0``13`即可.
44+
3045
```cpp
3146
// OJ: https://leetcode-cn.com/problems/qiu-12n-lcof/
3247
// Author: github.com/lzl124631x

0 commit comments

Comments
 (0)