[剑指Offer]求1+2+3+...+n的值(未完待续)
求1+2+3+...+n_牛客网
https://www.nowcoder.com/practice/7a0da8fc483247ff8800059e12d7caf1?tpId=13&tqId=11200&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
题目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
分析
题目明确说明不能使用乘除法和 for、while 等循环语句,那么通过等差数列求和公式和循环相加的方法求解就不符合题目要求了。
除了这些基本运算符,还有一种运算就是位运算,Java 中的位运算说明如表 1 所示。
表1 Java 中的位运算说明表
运算符 | 描述 |
& | 与 |
| | 或 |
^ | 异或 |
~ | 取反 |
>> | 左移 |
<< | 右移 |
>>> | 无符号右移 |
下面是位运算的一些例子。
10011 & 10101 = 10001
10011 | 10101 = 10111
10011 ^ 10101 = 00110
~ 10011 = 01100 (~ 01100 = 10011,即取反操作的逆操作结果即为本身)
~10101 = 01010
10011 << 3 = 1001100 (左移运算相当于 10011 的十进制数乘以 2 的 3 次方,因为位运算是底层的操作,所以乘以 2 的操作用左移比较快)
代码
public class Solution { public int Sum_Solution(int n) { int sum = (int)(Math.pow(n, 2) + n); return sum >> 1; } }