标题: [Microsoft面试]题目:求1+2+…+n, [打印本页] 作者: 陈荣莲 时间: 2013-8-16 10:49 标题: [Microsoft面试]题目:求1+2+…+n, 要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)。作者: 秦静静 时间: 2013-8-16 11:09
1+..+n=n*(n+1)/2=(n^2+n)/2it is easy to get x/2, so the problem is to get n^2though no if/else is allowed, we can easilly go around using short-pass.using macro to make it fancier:#define T(X, Y, i) (Y & (1<<i)) && X+=(Y<<i)intfoo(int n){ int r=n; T(r, n, 0); T(r, n,1); T(r, n, 2); … T(r, n, 31); return r >> 1;}