求a^b
直接求解,需要循环b次。
思路:
将b转化为二进制。对应为1的次数的幂保留,只需要将保留的幂的结果进行乘积就是a**b。
class Solution():
def fast(self, a,b):
b = bin(b)[2:]
res = 1
for i in b[::-1]:
if i == '1':
res = res * a
a *= a
return res
#include<iostream> // 如果使用# include<bits/stdc++.h> 会直接导入所有常用的头文件,编译时间长
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
int res = 1;
while(b){
if (b & 1) res = res * 1ll * a;
a = a * 1ll * a; //这里的1ll(一LL)是将a强制类型转换为longlong
b >> 1;
}
cout << res << endl;
return 0;
}
求 a*b
class Solution():
def fast(self, a, b):
res = 0
b = bin(b)[2:]
for i in b[::-1]:
if i == '1':
res += a
a *= 2
return res
#include<iostream>
using namespace std;
typedef unsigned long long ULL;
int main(){
ULLa, b;
cin >> a >> b;
ULL res = 0;
while(b):{
if(b&1) res += a;
a *= 2
b >>= 1
}
cout << res << endl;
return 0;
}