bit manipulation - Bitwise operations in java -
what piece of code mean ...can explain how work..
sum += (i & (1<<j)) != 0 ? n[j] : 0;
full code:
int max = (1 << n)-1; //system.err.println(max); string res = "no"; (int = 0; <= max; i++) { long sum = 0; (int j = 0; j < n; j++) { sum += (i & (1<<j)) != 0 ? n[j] : 0; } //system.err.println(i + " " + sum); if(sum == m){ res = "yes"; break; }
let's a = 0011 1100
so binary left shift operator (<<). left operands value moved left number of bits specified right operand.
a << 2 give 240 1111 0000
so in code have loop , loop j
and line
sum += (i & (1<<j)) != 0 ? n[j] : 0;
so second iteration of = 2 , first iteration of j = 1
first left shift operator shift left bits 1 position, resulting in 0000 0001 << 1 = 0000 0010 (or 2)
then have binary and
comparison (0000 0010 in binary) & (0000 0010) = 0000 0010 (or 2)
and and
result asked if it's distinct of zero. if result it's true sum
increased number in n[j]
array position, else not increased.
java has shortened version of if else command. use of easy, once understand it.
it’s written:
x ? y : z;
here question mark , colon take place of commands if , else. means:
condition ? incaseoftrue : elsecase;
Comments
Post a Comment