Home > Backend Development > C++ > 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

王林
Release: 2023-08-26 14:01:14
forward
860 people have browsed it

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
Copy after login

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;
}
Copy after login

Input

"1000"
Copy after login

Output

2
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template