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