Quote:
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);
}
Indentation style - Wikipedia[
^]
Professional programmer's editors have this feature and others ones such as parenthesis matching and syntax highlighting.
Notepad++ Home[
^]
ultraedit[
^]
Quote:
How can I write the same function by using exactly one loop
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;
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
...
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.