总结:1、找不出错误时,穷举题解测试数据跟错误方法对比,输出不一样的值,再单独分析
2、截止到找到某个数,应该用while更靠谱,及时终止;别乱用双重循环
3、swap比我靠谱
As we known, data stored in the computers is in binary form. The problem we discuss now is about the positive integers and its binary form.
Given a positive integer I, you task is to find out an integer J, which is the minimum integer greater than I, and the number of '1’s in whose binary form is the same as that in the binary form of I.
For example, if “78” is given, we can write out its binary form, “1001110”. This binary form has 4 '1’s. The minimum integer, which is greater than “1001110” and also contains 4 '1’s, is “1010011”, i.e. “83”, so you should output “83”.
输入
One integer per line, which is I (1 <= I <= 1000000).
A line containing a number “0” terminates input, and this line need not be processed.
输出
One integer per line, which is J.
题目本身不难,贪心算法方面不存在问题,问题在于细节处理以及错误的分析过程
错误题解(简单模拟,但存在特殊解处理不当,导致无法ac)
char a[65];
char *tobin(int x) {
memset(a, 0, sizeof(a));
int i = 0;
while (x != 0) {
a[i] = x % 2 + '0';
x /= 2;
i++;
}
a[i] = '\0';
return a;
}
int huanyuan(char a[]) {
int i, ans = 0;
for (i = strlen(a) - 1; i >= 0; i--) {
ans *= 2;
ans += a[i] - '0';
}
return ans;
}
int main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout)