思路:將k看做二進制數,每次與1,若獲得結果爲1,就相乘.ios
#include<iostream> using namespace std; int main() { int n = 2, k = 8; int res = 1; cout<<n<<"的"<<k<<"次方等於:"; while(k) { if(k & 1) { res *= n; } n *= n; k >>= 1; } cout<<res<<endl; return 0; }