标签:white ace while data ble container over end level
题目:
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路:
自己解答:
犯的错误:
java数组 class[] a = new class[n]
只是构建这一块空间,不会让构造函数运行这么多次
注意:
别人解答:
方法一:递归实现1+2+..+n;
public static int Sum_Solution(int n) {
int sum = n;
boolean flag = (sum > 0) && ((sum += Sum_Solution(--n)) > 0);
return sum;
}
方法三,利用Math实现n(n+1)
public static int Sum_Solution1(int n) {
return (int) (Math.pow(n, 2) + n) >> 1;
}
方法二:n(n+1)/2,递归实现n(n+1);
先参考使用while的例子,再转换
原理是把a拆成2的幂的和,a = 2^e0 + 2^e1 + 2^e2....
那么 a * b = (2^e0 + 2^e1 + 2^e2+...) * b
= b * 2^e0 + b * 2^e1 + b * 2^e2 + ...
= (b << e0) + (b << e1) + ....
public static int Sum_Solution2(int n) {
int res = 0;
int a = n;//若a=2=10
int b = n + 1;//b=3=11
while (a != 0) {
if ((a & 1) == 1)//a在第二位==1的时候才更新res=0+110=6
res += b;
a >>= 1;//a右移1位 1
b <<= 1;//b左移动1位 110
}
return res>>=1;//n(n+1)/2 }
接下来,用(a & 1) == 1和(a != 0)来代替判断语句
public int Sum(int n) {
int res = multi(n, n + 1);//n*(n-1)
return res>>=1;//n*(n-1)/2
}
private int multi(int a, int b) {
int res = 0;
//循环体内部, if ((a & 1) == 1), res += b;
boolean flag1 = ((a & 1) == 1) && (res += b) > 0;
a >>= 1;
b <<= 1;
// while (a != 0) {}循环条件
boolean flag2 = (a != 0) && (res += multi(a,b)) > 0 ;
return res;
}
标签:white ace while data ble container over end level
原文地址:https://www.cnblogs.com/muche-moqi/p/12393052.html