+ 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.

25th Jan 2018, 7:23 PM
Akash papnai
Akash papnai - avatar
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^^
25th Jan 2018, 8:44 PM
Shadow
Shadow - avatar
+ 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.
26th Jan 2018, 6:29 PM
Shadow
Shadow - avatar
+ 1
@naitomea Will the time complexity of this statement be O(1)?
26th Jan 2018, 1:24 PM
Akash papnai
Akash papnai - avatar
+ 1
thanks.....
26th Jan 2018, 6:30 PM
Akash papnai
Akash papnai - avatar
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
25th Jan 2018, 9:18 PM
Andres0b0100
Andres0b0100 - avatar
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.
25th Jan 2018, 9:21 PM
Andres0b0100
Andres0b0100 - avatar