I tried to figure out how this program works, and I got stuck at While loop, I don't understand how the second loop exit, since the v
will never end up equal to 0 or negative. Since it's the only conditions that would exit that loop, or am I missing something deeper? The code converts integers (>0) into binary.
public class Binary {
public static void main(String[] args) {
// read in the command-line argument
int n = Integer.parseInt(args[0]);
// set v to the largest power of two that is <= n
int v = 1;
while (v <= n/2) {
v = v * 2;
}
// check for presence of powers of 2 in n, from largest to smallest
while (v > 0) {
// v is not present in n
if (n < v) {
System.out.print(0);
}
// v is present in n, so remove v from n
else {
System.out.print(1);
n = n - v;
}
// next smallest power of 2
v = v / 2;
}
System.out.println();
}
}
v is an int, and in Java 1/2 as an int gives 0. Your loop goes through all the powers of two so will reach one, and then 0.
Run it in a debugger to see!
Think to start with
n=10
so
v=8
the system will print
1010
and the iterations are:
1 - 10>8 else statement so print 1 and: n=2, v=4
2 - 2<4 if statement so print 0 and: v=2
3 - 2=2 else statement so print 1 and: n=0, v=1
4 - 0<1 if statement so print 0 and: n=0, v=1/2 that is 0 as integer
During the next iteration while condition it is not satisfied anymore and the code ends.
I feel that you have a problem in understanding the Integer Division . In integer division, 3/2
does not equal to 1.5
but instead it is 1
. So similarly 1/2
is not equal to 0.5
but instead it is 0
. Since variable v
is integer the division by integer 2
is always integer division. So your variable v
will ultimately reach 0
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.