{
"$type": "site.standard.document",
"canonicalUrl": "https://rednafi.com/python/check-is-a-power-of-two/",
"description": "Use Python's bit_count() method to elegantly check if an integer is a power of two by counting on-bits in binary representation.",
"path": "/python/check-is-a-power-of-two/",
"publishedAt": "2022-01-21T00:00:00.000Z",
"site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
"tags": [
"Python",
"TIL"
],
"textContent": "To check whether an integer is a power of two, I've deployed hacks like this:\n\nWhile this [hex trick works], I've never liked explaining the pattern matching hack that's\ngoing on here.\n\nToday, I came across this [tweet by Raymond Hettinger] where he proposed an elegant solution\nto the problem. Here's how it goes:\n\nThis is neat as there's no hack and it uses a mathematical invariant to check whether an\ninteger is a power of 2 or not. Also, it's a tad bit faster.\n\nExplanation\n\n> Any integer that's a power of 2, will only contain a single 1 in its binary\n> representation.\n\nFor example:\n\nThe .bit_count() function checks how many on-bits (1) are there in the binary\nrepresentation of an integer.\n\nComplete example with tests\n\n\n\n\n[hex trick works]:\n https://twitter.com/rednafi/status/1484326191687696391/photo/1\n\n[tweet by raymond hettinger]:\n https://twitter.com/raymondh/status/1483948152906522625",
"title": "Check whether an integer is a power of two in Python"
}