如何通过使用一个循环来编写相同的函数 [英] How can I write the same function by using exactly one loop
问题描述
<pre>static void fun(int x) {
int a, b, c, d;
d = 1;
for (a = 1; a <= x; a++) {
b = a;
c = 1;
while (b > 0) {
c &= b % 2;
b /= 2;
}
d += c;
}
System.out.println(d);
}
我的尝试:
我试图将while循环更改为if循环,然后在循环将新值赋给变量之后,我尝试使用continue;但结果却截然不同。我也试图摆脱for循环并在没有循环的情况下递增a值,但结果也不同。
What I have tried:
I have tried to change the while loop into if loop and then after the loop assigns the new values to the variables, I have tried to use continue; but results has been completely different. I have also attempted to get rid of the for loop and increment the a value without a loop but result has been different also.
推荐答案
static void very_fun(int x)
{
int b = 1, c = 1;
for (int a = 1; a <= x; a += b)
{
++c;
b *= 2;
}
System.out.println(c);
}
你需要的是一个递归函数。
DuckDuckGo的java递归函数 [ ^ ]
What you need is a recursive function.
java recursive functions at DuckDuckGo[^]
我试过继续使用;但结果完全不同。
I have tried to use continue; but results has been completely different.
尝试随机更改代码是一个坏主意。
学会正确缩进你的代码,它显示其结构,它有助于阅读和理解。它还有助于发现结构错误。
Trying random changes in code is a bad idea.
Learn to indent properly your code, it show its structure and it helps reading and understanding. It also helps spotting structures mistakes.
static void fun(int x) {
int a, b, c, d;
d = 1;
for (a = 1; a <= x; a++) {
b = a;
c = 1;
while (b > 0) {
c &= b % 2;
b /= 2;
}
d += c;
}
System.out.println(d);
}
缩进风格 - 维基百科 [ ^ ]
专业程序员的编辑有这个功能和其他功能,如括号匹配和语法高亮。
Notepad++主页 [ ^ ]
ultraedit [ ^ ]
Indentation style - Wikipedia[^]
Professional programmer's editors have this feature and others ones such as parenthesis matching and syntax highlighting.
Notepad++ Home[^]
ultraedit[^]
怎么能我通过使用一个循环来编写相同的函数
How can I write the same function by using exactly one loop
在第一次阅读时,看起来需要2个循环,所以如果你必须将它保存在1个函数中,你需要完全理解这段代码是做什么的。
这个
On first reading, it looks like the 2 loops are needed, so if you have to keep it in 1 function, you need to fully understand what is doing this code.
This
c &= b % 2;
b /= 2;
告诉代码正在弄乱<$的二进制形式c $ c> b
首先要做的是运行x = 1,2,3,4 ... 16的函数
备注匹配结果和二进制x
tells that the code is messing with the binary form of b
first thing to do is run the function with x=1, 2, 3, 4 ... 16
note matching results and binary of x
x binary result
1 1
2 10
3 11
...
然后你必须找到结果改变的原因,这种理解可能导致简化和循环移除。
否则,CPallini的解决方案只是神奇的,你什么都不会学到。
then you have to find the reason why result change, this understanding may lead to simplify and a loop removal.
Otherwise, CPallini's solution is just magic and you will learn nothing.
这篇关于如何通过使用一个循环来编写相同的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!