Skip to content

Commit 891c214

Browse files
committed
面试题64. 求1+2+…+n
1 parent 40fb94d commit 891c214

File tree

1 file changed

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

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# [面试题64. 求1+2+…+n](https://leetcode-cn.com/problems/qiu-12n-lcof/)
2+
3+
<div class="content__1Y2H"><div class="notranslate"><p>求 <code>1+2+...+n</code> ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。</p>
4+
5+
<p>&nbsp;</p>
6+
7+
<p><strong>示例 1:</strong></p>
8+
9+
<pre><strong>输入:</strong> n = 3
10+
<strong>输出:&nbsp;</strong>6
11+
</pre>
12+
13+
<p><strong>示例 2:</strong></p>
14+
15+
<pre><strong>输入:</strong> n = 9
16+
<strong>输出:&nbsp;</strong>45
17+
</pre>
18+
19+
<p>&nbsp;</p>
20+
21+
<p><strong>限制:</strong></p>
22+
23+
<ul>
24+
<li><code>1 &lt;= n&nbsp;&lt;= 10000</code></li>
25+
</ul>
26+
</div></div>
27+
28+
## Solution 1.
29+
30+
```cpp
31+
// OJ: https://leetcode-cn.com/problems/qiu-12n-lcof/
32+
// Author: github.com/lzl124631x
33+
// Time: O(1)
34+
// Space: O(1)
35+
class Solution {
36+
int d(unsigned n, int i) {
37+
return -((n >> i) & 1) & (n << i);
38+
}
39+
public:
40+
int sumNums(int n) {
41+
return (d(n, 0) + d(n, 1) + d(n, 2) + d(n, 3) + d(n, 4) + d(n, 5) + d(n, 6)
42+
+ d(n, 7) + d(n, 8) + d(n, 9) + d(n, 10) + d(n, 11) + d(n, 12) + d(n, 13) + n) >> 1;
43+
}
44+
}
45+
```

0 commit comments

Comments
 (0)