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  s2[i], then:
      (increase f by 1)
   otherwise when s1[i]  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 
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  s2[i])
         f++;
      else if(s1[i]  s)
      cout f)
      cout

Input

231, 337, 3

Output

Second
Updated on: 2022-03-29T08:50:15+05:30

540 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements