输入一个十进制整数,输出对应的七进制结果.
例如:
Input1:
20
Output1:
26
Input2:
-100
Output2:
-202
题解:
- 根据辗转相除法,输入 num,每次将 num 对 7 取余,再将 num 除 7,直到 num 为 0 为止,得到的余数加入到一个字符串中,对这个字符串翻转之后就是 num 对应的 7 进制数.
- 特别注意一下对正负号的处理.
C++ code:
#include2using 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; }
给定一个 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:
#includeusing 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; }



