AcWing 428. 数列
原题链接
简单
作者:
牛奶小柒Luke
,
2021-02-06 21:11:23
,
所有人可见
,
阅读 305
二进制
N = 1 --> 1 ---> 3^0
N = 2 --> 10 ---> 3^1
N = 3 --> 11 ---> 3^0+3^1
N = 4 --> 100 ---> 3^2
......
N转换为二进制,转为k为底计算
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
typedef long long LL;
int b = 1;
LL work(int k,int N){
int ans = 0;
while(N){
ans += N % 2 * b;
b *= k;
N /= 2;
}
return ans;
}
int main(){
int k,n;
cin >> k >> n;
printf("%lld",work(k,n));
}
N = 1 --> 1 ---> 3^0
N = 2 --> 10 ---> 3^1
N = 3 --> 11 ---> 3^0+3^1
N = 4 --> 100 ---> 3^2
......
找规律,看二进制中1的位数
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
typedef long long LL;
const int N = 20;
int k,n;
LL pow(int k,int n){
int ans = 1;
while(n--){
ans *= k;
}
return ans;
}
int main(){
cin >> k >> n;
LL ans = 0;
for(int i = 0;i < N;++i){
if(n >> i & 1){
ans += pow(k,i);
}
}
printf("%lld",ans);
return 0;
}