给定两个正整数N和K。找到可以从数字N中删除的最小位数,这样在删除之后该数字可以被10K整除。如果不可能,则打印-1。
如果N = 10203027和K = 2,那么我们必须删除3位数字。如果我们删除3、2和7,则数字变为10200,可被102整除
1. Start traversing number from end. If the current digit is not zero, increment the counter variable, otherwise decrement variable K 2. If K is zero, then return counter as answer 3. After traversing the whole number, check if the current value of K is zero or not. If it is zero, return counter as answer, otherwise return answer as number of digits in N –1 4. If the given number does not contain any zero, return -1 as answer
#include <bits/stdc++.h> using namespace std; int getBitsToBeRemoved(int n, int k) { string s = to_string(n); int result = 0; int zeroFound = 0; for (int i = s.size() - 1; i >= 0; --i) { if (k == 0) { return result; } if (s[i] == '0') { zeroFound = 1; --k; } else { ++result; } } if (!k) { return result; } else if (zeroFound) { return s.size() - 1; } return - 1; } int main() { int n = 10203027; int k = 2; cout << "Minimum required removals = " << getBitsToBeRemoved(n, k) << endl; return 0; }
当您编译并执行上述程序时。它产生以下输出
输出结果
Minimum required removals = 3