【bit check solution】求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
Steps:
1. 提取最后一个bit作为奇偶数标志位
2. tmp存储前偶数个数字的和
3. 最后加上n(奇数情况) or 0(偶数情况)
奇数情况:1 + 2 + 3 + 4 + 5 --> (1 + 2 + 3 + 4) + 5 * 1
偶数情况:1 + 2 + 3 + 4 --> (1 + 2 + 3 + 4) + 4 * 0
public class Solution { public int Sum_Solution(int n) { int odd = n & 0x1; int tmp = n - odd; int ans = (tmp + 1) * (tmp / 2); return ans + odd * n; } }