+ 1
I'm confused with this line. Can anyone explain?
((i&1)&&cout<<"odd")||cout<<"even"; Here i is the input to the program to check for even or odd case. Please also help with time complexity of the program.
6 odpowiedzi
+ 4
The & works in this case as the binary AND operator.
It compares two numbers in binary format and sets a bit to true/1 at each position where both numbers have a true bit.
An example might explain it easier:
i = 9 => 1010
j = 12 => 1100
i & j will be
1000 => 8
Now if you use it with 1, only the last bit can be set, because 1 in binary is ...0001, resulting in either 1 (true) or 0 (false).
The cout statements will be evaluated as true.
Next, if the last bit is set to true, a number is odd.
In this case the AND-case will be true && true and therefore "odd" is printed.
If a number is even - last bit is false - the AND case will be false && true, therefore false, but the OR case will be evaluated as true (false || true) and "even" will be printed.
Also, the parentheses in the entire expression are not necessary since && has a higher precedence than ||.
Im sorry for the long text, but your question was not very specific, so I thought I'd might explain it all aswell^^
+ 2
@Akash Im sorry, but I have no idea how to calculate time complexity (I didnt even know about it before you mentioned it, had to search the internet myself^^), thats a question for someone who is deeper into that stuff.
+ 1
@naitomea Will the time complexity of this statement be O(1)?
+ 1
thanks.....
0
(i&1) is true if the first bit of i is 1, it means that it's even
If it's false, the program won't execute the (cout<<"odd") statement because if any operand is false, the operation && is false
If it's true, the program won't execute the (cout<<"even") statement because if any operand is true, the operation || is true
0
A && B => A is True? Then check B. A is False? Then return False.
A || B => A is True? Then return True. A is False? Then check B.