Skip to content

Commit de0d42a

Browse files
committed
1 parent 6075c49 commit de0d42a

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

Sum_Solution.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
* 题:求1+2+...+n,要求不能使用乘除法、for、while、if、else、switch、case等
3+
* 关键字及条件判断语句(A?B:C)
4+
*/
5+
class solution{
6+
public:
7+
int Sum_Solution(int n){
8+
/*
9+
* 因为1+2+...+n=n(n+1)/2,这里把乘法用位操作写出来
10+
* a*b(a>b,这样可以让循环次数少一点)等价于
11+
* res=0;
12+
* while(b){ b=b0*2^0+b1*2^1+...+bn*2^n
13+
* if(b&0x1) res+=a; 若b0=1,res=res+a
14+
* a<<=1; a<<=1等价于a*2
15+
* b>>=1; b>>=1等价于b/2,此时b=b1*2^0+...bn*2^n-1
16+
* }
17+
*/
18+
int a=n+1,res=0;
19+
while(n){
20+
if(n&0x1)
21+
res+=a;
22+
a<<=1;
23+
n>>=1;
24+
}
25+
res>>=1;
26+
return res;
27+
}
28+
}
29+
/*
30+
* 还看到别人有种做法是利用了逻辑与&&的短路特性,但是这个方法的复杂度是O(n)
31+
* 我的方法复杂度是O(logn),n变得很大时就会有速度的差异
32+
*/
33+
class solution{
34+
public:
35+
int Sum_Solution(int n){
36+
int res=n;
37+
//当递归到res=n=0时,逻辑表达式遇到前项res=0就不再计算后项
38+
res&&(res+=Sum_Solution(n-1));
39+
return res;
40+
}
41+
}

0 commit comments

Comments
 (0)