求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
-
利用Math.pow方法和移位运算
public class Solution {
public int Sum_Solution(int n) {
//Math.pow方法,(double a, double b)。 相当于a ^ b
// >> <<左移右移运算符,如果强制转换为int.则相当于乘2或者除2
return(int) (Math.pow(n,2) + n) >> 1;
}
}
-
利用短路&&来实现if的功能,从而利用递归解题
public class Solution {
public int Sum_Solution(int n) {
int sum = n;
boolean flag = (sum > 0) && ((sum += Sum_Solution(--n)) > 0);
return sum;
}
}
&&短路法需要进一步理解