牛牛给你一个只包含字符1到9的字符串S, 你现在可以在任意两个数字字符之间插入'+'号构成一个式子,现在希望你能求出所有式子的结果之和。

判断是否是素数

// 判断是否为质数:
//小于2的数不是质数。
//遍历 2 到 √n,若存在因子则非质数。
bool isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; i <= sqrt(n); ++i)
        if (n % i == 0) return false;
    return true;
}

 

链接:https://ac.nowcoder.com/acm/contest/3286/C
来源:牛客网
牛牛给你一个只包含字符1到9的字符串S, 你现在可以在任意两个数字字符之间插入'+'号构成一个式子,现在希望你能求出所有式子的结果之和。

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;
vector<vector<string>> expressions;
vector<string> path;
// 深度优先搜索生成所有可能的表达式
void dfs(const string& s, int startIndex) {
    if (startIndex == s.length()) {
        expressions.push_back(path);
        return;
    }

    for(int i = startIndex; i < s.size(); i++) {
        string str = s.substr(startIndex, i - startIndex + 1);
        path.push_back(str);
        dfs(s,i+1);
        path.pop_back();
    }
}


long long evaluate(const vector<string>& expr) {
    long long sum = 0;
    for (auto num : expr){
        sum += stoll(num);
    }
    return sum;
}

long long addPlus(const string& input) {
    if (input.empty()) return 0;

    dfs(input, 0);

    long long total = 0;
    for (auto expr : expressions) {
        total += evaluate(expr);
    }

    return total;
}

int main() {
    string num;
    cin >> num;
    cout << addPlus(num) <<endl;
    return 0;
}

 判断素数

https://blog.csdn.net/alazyperson/article/details/104083695

posted @ 2025-07-09 16:07  最近饭吃的很多  阅读(26)  评论(0)    收藏  举报