文章出處

題目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等關鍵字及條件判斷語句(A?B:C)。

這題目簡直沒事找事...為啥這么說,因為沒有限制的話用等差數列求和公式直接算出結果,有限制的話是希望用遞歸的思想來做。但是明明有通式了還用遞歸做,又傻又費內存。

換個思路,先取log再e回去,這樣避免了乘法。除法的話因為只需要除以2,那就用移位操作。

提交發現有小數的坑,需要+0.5再取整。

class Solution {
public:
    int Sum_Solution(int n) {
        //return n*(n+1)/2;
        return multi(n, n + 1) >> 1;
    }
    int multi(int a, int b){
        // we can guarantee that both a and b is positive integers
        int res = int(pow(10, log10(a) + log10(b))+0.5);
        return res;
    }
};

文章列表


不含病毒。www.avast.com
全站熱搜
創作者介紹
創作者 大師兄 的頭像
大師兄

IT工程師數位筆記本

大師兄 發表在 痞客邦 留言(0) 人氣()