第五届字节跳动青训营 - 前端笔试练习题代码分享

1,051 阅读2分钟

4的幂

题目描述

image.png

思路

题目没有给出数据范围。但是请注意:题目给出的是一个整数字符串, 以常规1e5来计, do while方法是不可行的。需要用到大数模拟

如果一个数是4的幂, 则这个数被4一直整除, 最后的余数应该为1.
利用大数模拟, 在模拟之前先对数字进行判断, 如果不能被4整除则输出false
否则一直运算, 直到不能被4整除或者结果为1

时间复杂度: 大数除法的复杂度是O(n), 而我们会进行不超过200次运算, 极限情况下是2e72e7次运算

4^100 = 1,606,938,044,258,990,275,541,962,092,341,162,602,522,202,993,782,792,835,301,376
len = 61

代码

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

string str;

pair<string, int> div(string s, int k) {
    // 商和余数
    string res;
    int r = 0;

    // 经典大数除法
    for (char i : s) {
        r = 10 * r + (i - '0');
        if (!res.empty() && r / k != 0) res += to_string((r / k) + '0');
        r = r % k;
    }

    return {res, r};
}

int main() {
    cin >> str;
    pair<string, int> p;
    // 如果降到个位数就退出
    while (str.length() > 1) {
        p = div(str, 4);
        str = p.first;
        if (p.second != 0) break; // 如果没有整除就退出
    }

    // 最后判断结果
    if ((str == "4" || str == "1") && p.second == 0) cout << "true" << endl;
    else cout << "false" << endl;
    return 0;
}

回文串

题目描述

image.png

思路

题目说只考虑字母和数字字符, 求是否是回文串

代码

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

string str;

int main() {
    cin >> str;
    string t = "";
    for (auto i : str) {
        if (i >= '0' && i <= '9') t += i;
        else if (i >= 'a' && i <= 'z') t += i - 32;
        else if (i >= 'A' && i <= 'Z') t += i;
    }
    string s = t;
    reverse(s.begin(), s.end());
    if (s == t) cout << "true" << endl;
    else cout << "false" << endl;
    return 0;
}

最长回文子串

题目描述

image.png

思路

题目的示例1应该结果为1

字符串类的经典题目, 遇到过一篇写的好的文章
最长回文子串_-CSDN

代码

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

string str;

int main() {
    cin >> str;
    string s = "#";
    for (auto i: str) {
        s += i;
        s += "#";
    }
    int n = s.length();
    vector<int> d1(n);
    for (int i = 0, l = 0, r = -1; i < n; i++) {
        int k = (i > r) ? 1 : min(d1[l + r - i], r - i + 1);
        while (0 <= i - k && i + k < n && s[i - k] == s[i + k]) {
            k++;
        }
        d1[i] = k--;
        if (i + k > r) {
            l = i - k;
            r = i + k;
        }
    }
    int res = 0;
    for (int i = 0; i < n; i++) res = max(res, d1[i] - 1);
    cout << res << endl;
    return 0;
}