Be concise.
Be useful.
All contributions dictatorially edited by webmasters to match personal tastes.
Please do not paste any copyright violating material.
Please try to avoid dependencies to third-party libraries and frameworks.
let p = i.count_ones() % 2;
parity(Number) -> parity(Number, 0).
parity(Number, Count) when Number band 1 == 1 ->
parity(Number bsr 1, Count + 1);
parity(Number, Count) when Number > 0 ->
parity(Number bsr 1, Count);
parity(_, Count) ->
Count rem 2.
print *,poppar(i)
let i = 42
i.toString(2)
.split('')
.reduce((parity, bit) => parity ^ bit, 0)
int p = Integer.bitCount(i) % 2;
function Parity(n: Integer): Integer;
var
Mask, I, Bits: Integer;
begin
Bits := 0;
for I := 0 to SizeOf(Integer)*8 - 1 do
begin
Mask := 1 shl I;
if ((n and Mask) <> 0) then Inc(Bits);
end;
Result := Ord(Odd(Bits));
end;
begin
writeln(Parity(42));
end.
Ord(False) equals 0
function Parity(n: Int32): Integer;
begin
Result := Ord(Odd(PopCnt(DWORD(n))));
end;
var
i: Int32;
begin
i := 42;
writeln('Parity(42) = ',Parity(i));
end.
PopCnt returns the number of set bits, it only accepts unsigned parameters, hence the typecast to DWORD (also 32-bit).
$p = ($count = @ones = (sprintf '%b', $i) =~ /1/g) % 2;
sprintf %b converts the integer $i into a string of zeros and ones. This is matched against a '1' repeatedly (courtesy of the g regex modifier). The result of that is a list of matches returned into list variable @ones.
The list variable @ones is then assigned to scalar $count, which yields a count of the list items.
Modulo 2 of the count is then taken in order to get the parity. If the number of bits is odd, then there will be a one remainder, and one is taken as true by Perl
The list variable @ones is then assigned to scalar $count, which yields a count of the list items.
Modulo 2 of the count is then taken in order to get the parity. If the number of bits is odd, then there will be a one remainder, and one is taken as true by Perl
p = bin(i).count('1') % 2
p = i.digits(2).count(1)[0]
(define (popcount x)
(let loop ([s x]
[count 0])
(cond [(zero? s) count]
[(odd? s) (loop (arithmetic-shift s -1) (add1 count))]
[else (loop (arithmetic-shift s -1) count)])))
(define i 42)
(popcount i)
Named let is a common way to iterate in Scheme because it allows for tail recursion.