
讨论一个给定二进制数的问题。我们必须从中删除一点,以便剩余的数字应该是所有其他选项中的最大值,例如
Input : N = 1011 Output: 111 Explanation: We need to remove one bit so removing 0 bit will give a maximum number than removing any 1’s bit. 111 > 101, 011. Input: 111 Output: 11 Explanation: Since all the bits are 1 so we can remove any bit.
暴力破解会给出最大的结果数,即通过一位一位去除,比较不同的结果,并获得最大结果。
但是它可以使用一种高效方法,即,如果我们删除最少的冗余位。
高效的方法对结果的影响最小。
立即学习“C++免费学习笔记(深入)”;
首先,从右边开始遍历各个位。
搜索 0 并将其在第一个计数器上删除。
如果未找到 0,则删除任何位。
高效方法的 C++ 代码
#include <bits/stdc++.h>
using namespace std;
int main(){
string str = "1011";
bool flag = false;
int n = str.length();
// Initialising new array for
char res[n - 1];
int j = 0;
// traversing through the binary number from right.
for (int i = 0; j < n - 1; i++) {
// if 0 is found then skip it.
if (str[i] == '0' && flag == false) {
flag = true;
continue;
}
else
res[j++] = str[i];
}
// printing the resulting string.
cout << "Maximum number: " << res;
return 0;
}Maximum number: 111
使用标志变量,以便只消除一个 0。
初始化字符数组 res 来存储结果数。
循环将运行到 n-1,因为我们需要存储比原始数少一个元素。
循环将运行到 n-1。 p>
在本教程中,我们讨论了删除一位后找到最大数字。我们讨论了解决此问题的两种方法。
我们还为此编写了 C++ 代码,我们可以用任何其他语言(如 C、Java、Python 等)编写这些代码。我们希望本教程对您有所帮助。
以上就是在C++中,将一个二进制数的一位移除以获得最大值的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号