Home  >  Article  >  Backend Development  >  C++ program to find the minimum number of operations required to make a number 0

C++ program to find the minimum number of operations required to make a number 0

王林
王林forward
2023-08-26 14:01:14796browse

C++ program to find the minimum number of operations required to make a number 0

Suppose we have a numeric string S containing n digits. Suppose S represents a digital clock and the entire string displays integers from 0 to 10^n - 1. If there are fewer digits, leading 0s are shown. Follow these steps -

  • decrement the number on the clock by 1, or

  • swap the two digits p>

We want the clock to display 0 with the minimum number of operations. We have to calculate the number of operations required to complete this operation.

So if the input is something like S = "1000" the output will be 2 as we can swap the first 1 with the last 0 so the string will be "0001" now subtract 1 from it we get "0000".

Steps

To solve this problem we will follow the following steps-

n := size of S
x := digit at place S[n - 1]
for initialize i := 0, when i <= n - 2, update (increase i by 1), do:
   if S[i] is not equal to &#39;0&#39;, then:
      x := x + (digit at place S[i]) + 1
return x

Example

Let us see the following implementation for better understanding Understanding-

#include <bits/stdc++.h>
using namespace std;

int solve(string S) {
   int n = S.size();
   int x = S[n - 1] - &#39;0&#39;;
   for (int i = 0; i <= n - 2; i++)
      if (S[i] != &#39;0&#39;)
         x = x + S[i] + 1 - &#39;0&#39;;
   return x;
}
int main() {
   string S = "1000";
   cout << solve(S) << endl;
}

Input

"1000"

Output

2

The above is the detailed content of C++ program to find the minimum number of operations required to make a number 0. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete