【C++】牛客网金典面试题

目录

1.不可以运算符重载的操作符

 2.常成员函数

3.参数解析

4.跳石板

5.计算日期到天数转换

 6.幸运袋子


1.不可以运算符重载的操作符

*    三目操作符     ::       .      sizeof

 2.常成员函数

这种函数只能读取成员变量的值,而不能修改

常成员函数的主要特点:

1)不能更新类的成员变量
2)不能调用该类中没有用const修饰的成员函数,即只能调用常成员函数
3)可以被类中其它的成员函数调用
4)常对象只能调用常成员函数,而不能调用其他的成员函数。

注意写法: 

3.参数解析

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
    string tmp = ""; //一个临时的字符串,用来存储每次分割的字符串
    string s; //题给字符串
    vector<string> v;
    getline(cin, s); //一定要用getline,cin会在空格处停止写入
    bool is = false; //判断是不是双引号
    for (int i = 0; i < s.size(); i++) { 
        if (s[i] == ' " ') //如果是双引号
            is = !is; //把is变成true
        else if (s[i] == ' ' && !is) { //如果遇到空格,并且不是双引号
            v.push_back(tmp); //把分割的子串压入
            tmp = ""; //tmp清空
        }
        else
            tmp += s[i]; //正常情况,直接+=
    }
    v.push_back(tmp); //最后一个子串不是以空格结尾,需要手动添加
    cout << v.size() << endl; //按照题给要求输出
    for (auto e : v)
        cout << e << endl;
}

4.跳石板

 这个题涉及到找每个数的因数,但是一定要注意找因子的时间复杂度.....

代码里面格子取不到的意思是

这样的格子不属于走因子步,所以我们把他放入(初始化)成一个很特殊的值,可以无穷大不在m的取值范围里 

5.计算日期到天数转换

这个很简单了 直接写 

#include <iostream>
using namespace std;
int main()
{
    int day[] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
    int y, m, d;
    cin >> y >> m >> d;
    if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0))
        day[2] = 29;
    int ans = 0;
    int i = m;
    while (--i)
        ans += day[i];
    ans += d;
    cout << ans << endl;
    return 0;
}

 6.幸运袋子

首先肯定把每个号码装在vector,然后对其排序,因为如果到某个数字,sum(求和)<=mul(乘积)那么排序之后更不会求和>乘积,这样节省我们思考的难度

然后要传每一次的sum和mul,还有开始遍历的起点

就正常按步骤计算即可 

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int is(vector<int> v, int n, int begin, int sum, int mul) //再次回来我还是这个sum和mul所以不需要引用
{
    int count = 0, i = begin;
    for (; i < n; i++)
    {
        sum += v[i]; mul *= v[i];
        if (i == 0 && sum == v[0]) is(v, n, i + 1, sum, mul);
        else
        {
            if (sum > mul)
                count += 1 + is(v, n, i + 1, sum, mul);

            else break;
            sum -= v[i]; //把现在的数字去掉,看看后面有没可能
            mul /= v[i];
            while (i < n - 1 && v[i] == v[i + 1]) //相同数字没必要纠结
                i++;
        }
    }
    return count;
}
int main()
{
    int n = 0; cin >> n;
    vector<int> v(n);
    for (auto& e : v)
    {
        cin >> e;
    }
    sort(v.begin(), v.end()); //一定要排序 要不然后面的就不知道是不是还满足要求,会超时...
    cout << is(v, n, 0, 0, 1) << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_71138261/article/details/129907623