题解 | #小红的字符生成#

小红的字符生成

https://www.nowcoder.com/practice/f8659377ca104b1aad45dd2fb564c940?tpId=376&tqId=2608571&ru=/exam/oj&qru=/ta/15-days-help/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E9%259D%25A2%25E8%25AF%2595%26topicId%3D376

题目解析:

a=a

b=aa

c=bb=aaaa

d=cc=bbbb=aaaa,aaaa

从而观察得到:

a=2^0*a

b=2^1*a

c=2^2*a

因此对于最少表达出n个a

也就是从1,2,4,8...2^t之中选最少的数求和来表示n

代码

#include "bits/stdc++.h"

using namespace std;
#define int long long
#define endl "\n"
#define PII pair<int,int>
#define PIII pair<int,PII>
const int MOD = 1e9 + 7;
const int N = 3e5;

void slu() {
    int n;
    cin >> n;
    string res;
    while (n) {
        int k = 0;
        while (pow(2, k) <= n)k++;
        k--;
        res.push_back(('a' + k));
        n -= pow(2, k);
    }
    cout << res;
}

signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int T;
//    cin >> T;
    T = 1;
    while (T--)slu();

}

全部评论

相关推荐

04-18 00:32
已编辑
中南大学 Java
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务