Home > Article > Backend Development > 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".
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 '0', then: x := x + (digit at place S[i]) + 1 return x
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] - '0'; for (int i = 0; i <= n - 2; i++) if (S[i] != '0') x = x + S[i] + 1 - '0'; return x; } int main() { string S = "1000"; cout << solve(S) << endl; }
"1000"
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!