C++ 中将数字中移除的次数最少化,以确保数字可以被 10 的 K 次幂整除
问题陈述
给定两个正整数 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
广告