
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
Find Minimum Operations to Make Number 0 in C++
Suppose we have a numeric string S with n digits. Consider S represents a digital clock and whole string shows an integer from 0 to 10^n - 1. If there are a smaller number of digits, it will show leading 0s. Follow the operations −
Decrease the number on clock by 1, or
Swap two digits
We want the clock will show 0 with minimum number of operations needed. We have to count the number of operations needed to do that.
So, if the input is like S = "1000", then the output will be 2, because we can swap first 1 with last 0, so the string will be "0001" now decrease it by 1 to get "0000".
Steps
To solve this, we will follow these 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
Example
Let us see the following implementation to get better 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; }
Input
"1000"
Output
2
Advertisements