Making a square() function without x*x in C++

后端 未结 7 2122
攒了一身酷
攒了一身酷 2020-12-31 14:44

I am self-studying C++ and the book \"Programming-Principles and Practices Using C++\" by Bjarne Stroustrup. One of the \"Try This\" asks this:

Implement square() wi

7条回答
  •  甜味超标
    2020-12-31 15:15

    Mats Petersson stole the idea out of my head even before I thought to think it.

    #include 
    
    template 
    T square(T x) {
        if(x < 0) x = T(0)-x;
        T sum{0}, s{x};
        while(s) {
            if(s & 1) sum += x;
            x <<= 1;
            s >>= 1;
        }
        return sum;
    }
    
    int main() {
        auto sq = square(80);
        std::cout << sq << "\n";
    }
    

提交回复
热议问题