题目链接:题目
大意:
给出一个“幸运数”,每一位都是4或7,问这是从1开始第几个幸运数。
思路:
直接暴力数复杂度太高,实际上就是看有多少种4和7组合。当然数组合也不能乱数,为了思路清晰我是从大数位往小数位(用字符串输入就是从头开始遍历)比如4747,先看4000,显然后三位数有8个幸运数,再看700,后两位有4个幸运数,因为最高位是7,还要乘2,以此类推。
另外还顺便写了快速幂,也就是a不断平方,如果b的二进制位为1则把a乘到ans上。
代码:
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define MOD 1000000007
#define fi first
#define se second
#define pii pair<int,int>
#define vec vector
int pw(int a, int b){
int ans = 1;
while(b > 0){
if(b & 1){
ans *= a;
}
a *= a;
b >>= 1;
}
return ans;
}
void solve(){
string s;
cin >> s;
int l = s.size(), ans = 0;
for(int i = 0; i < l; i++){
int x = pw(2, l - i - 1);
if(s[i] == '4'){
ans += x;
}else{
ans += 2 * x;
}
}
cout << ans << '\n';
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t=1;
while(t--){
solve();
}
return 0;
}