Title Description
Seeking 1 + 2 + 3 + ... + n, requires multiplication and division can not be used, for, while, if, else, switch, case and keywords such as conditional statement (A B:? C).
Ideas analysis
- A thought: he wrote with Math.pow calculated n (n + 1), then >> 1, that is n (n + 1) * 1/2
- Thinking two: big brother watching to know the answer && short-circuit characteristics. Implemented using a short-circuit characteristic is determined if n> 0 the function, which can be implemented recursively 1 + 2 + ... + n.
- Three ideas: one based on the idea advanced version, will split into a power of 2 and, a = 2 ^ e0 + 2 ^ e1 + 2 ^ e2 ...
then a * b = (2 ^ e0 + 2 ^ e1 + 2 ^ E2 + ...) * B
= B * 2 ^ E0 + B * 2 ^ E1 + B * 2 ^ E2 + ...
= (B << E0) + (B << E1) + ...
can not be used while writing, then the specific idea of two to a lot of trouble.
Short-circuit characteristic:
To make (Expression 1) && (Expression 2) requires the calculation result is true: expression 1, expression 2 are true. 1 If the expression is false, the expression 2 is not calculated, because the calculation result has been determined can not be true, that is the && short-circuit characteristic.
To make (Expression 1) || (Expression 2) requires the operation result is false: Expression 1, Expression 2 are false. 1 if the expression is true, the expression 2 is not calculated, because the calculation result has been determined possible false, this is the short-circuit operation || characteristics.
Code
public static int Sum_Solution(int n) {
int sum = n;
boolean flag = (sum > 0) && ((sum += Sum_Solution(--n)) > 0);
return sum;
}
public static int Sum_Solution1(int n) {
return ((int) Math.pow(n, 2) + n) >> 1;
}
public static int Sum_Solution2(int n) {
int res = 0;
int a = n, b = n + 1;
while (a != 0) {
if ((a & 1) == 1) {
res += b;
}
a >>= 1;
b <<= 1;
}
return res >>= 1;
}
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;
}