栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

记水题两道

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

记水题两道

1

输入一个十进制整数,输出对应的七进制结果.

例如:

Input1:

20

Output1:

26

Input2:

-100

Output2:

-202

题解:

  • 根据辗转相除法,输入 num,每次将 num 对 7 取余,再将 num 除 7,直到 num 为 0 为止,得到的余数加入到一个字符串中,对这个字符串翻转之后就是 num 对应的 7 进制数.
  • 特别注意一下对正负号的处理.

C++ code:

#include 

using namespace std;

int main() {
    int num;
    cin >> num;
    int symbol = 1;
    if (num < 0) {
        symbol = -1;
        num = -num;
    }
    string strAns = "";
    while (num > 0) {
        strAns += to_string(num - 7 * (int)(num / 7));
        num /= 7;
    }
    reverse(strAns.begin(), strAns.end());
    cout << symbol * stoi(strAns) << endl;
    return 0;
}
2

给定一个 N × M 大小的二维矩阵,再给定一个整数 threshold,如果矩阵中的某个数小于或等于 threshold,则将对应的行和列上的所有数变为 threshold,输出对应的矩阵.

输入第一行分别为 M、N 和 threshold

接下来的 N 行,每行有 M 个输入,表示二维矩阵.

输出对应的矩阵.

例如:

Input:

3 2 2
1 2 3
4 5 6

Output:

2 2 2
2 2 6

题解:

  • 扫描原矩阵,用两个哈希表分别记录小于等于 threshold 的元素所在的行和列;
  • 对于结果矩阵,如果其所在的行和列有其中之一在哈希表中可以查到,则该位置的元素值为 threshold,否则则为原数组中对应位置元素的值.

C++ code:

#include 

using namespace std;

int main() {
    int M, N, threshold;
    vector> matrix;
    vector> ans;
    unordered_set hashRows, hashCols;
    cin >> M >> N >> threshold;
    matrix.resize(N, vector(M, 0));
    ans.resize(N, vector(M, 0));
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            cin >> matrix[i][j];
            if (matrix[i][j] <= threshold) {
                hashRows.insert(i);
                hashCols.insert(j);
            }
        }
    }
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            if (hashRows.count(i) || hashCols.count(j)) {
                ans[i][j] = threshold;
            } else {
                ans[i][j] = matrix[i][j];
            }
        }
    }
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            cout << ans[i][j];
            if (j < M - 1) {
                cout << ' ';
            }
        }
        cout << endl;
    }
    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/832705.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号