C++ 代码找出哪个数字更大
假设我们有两个 k 位数 m 和 n。这两个数的数字被随机打乱比较。我们必须找出哪个数字更有可能更大。
因此,如果输入如下 n = 231, m = 337, k = 3,则输出为“Second”或第二个数字更有可能更大。
步骤
为了解决这个问题,我们将遵循以下步骤 -
s1 := convert n to string
s2 := convert m to string
f := 0, s = 0
for initialize i := 0, when i < k, update (increase i by 1), do:
if s1[i] > s2[i], then:
(increase f by 1)
otherwise when s1[i] < s2[i], then:
(increase s by 1)
if f > s, then:
print("First")
otherwise when s > f, then:
print("Second")
Otherwise
print("Equal")示例
让我们看以下实现,以便更好地理解 -
#include <bits/stdc++.h>
using namespace std;
#define N 100
void solve(int n, int m, int k) {
string s1 = to_string(n);
string s2 = to_string(m);
int f = 0, s = 0;
for(int i = 0; i < k; i++){
if(s1[i] > s2[i])
f++;
else if(s1[i] < s2[i])
s++;
}
if(f > s)
cout<<"First"<<endl;
else if(s > f)
cout<<"Second"<<endl;
else
cout<<"Equal"<<endl;
}
int main() {
int n = 231, m = 337, k = 3;
solve(n, m, k);
return 0;
}输入
231, 337, 3
输出
Second
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP