
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Code to Find Out Which Number Can Be Greater
Suppose, we are given two k-digit numbers m and n. The digits of the numbers are randomly shuffled and then compared. We have to find out which number has a higher probability to be greater.
So, if the input is like n = 231, m = 337, k = 3, then the output will be ‘Second’, or the second number has a higher probability to be greater.
Steps
To solve this, we will follow these steps −
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")
Example
Let us see the following implementation to get better understanding −
#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; }
Input
231, 337, 3
Output
Second
Advertisements