Checks whether a number is odd or even by using bitwise AND (&) operator.
Visualised
isOdd(9) // returns 1 (true)
1001 (9 in decimal)
0001 (1 in decimal)
&
----
0001
isOdd(6) // returns 0 (false)
0110 (6 in decimal)
0001 (1 in decimal)
&
----
0000 (0 in decimal)
Since odd numbers in binary always end with 1 at the lowest-order bit all we need is to check that bit and call it a day.
const isOdd = n => n & 1
const number = prompt("Enter a number: ");if(number % 2 == 0){console.log("The number is even.");}else{console.log("The number is odd.");}- const isOdd = n => n & 1
const chai = require("chai"); const assert = chai.assert; chai.config.truncateThreshold=0; describe("Small numbers", () => { it("odd ones return truthy", () => { assert.isOk(isOdd(1)); assert.isOk(isOdd(3)); assert.isOk(isOdd(5)); assert.isOk(isOdd(007)); assert.isOk(isOdd(9)); assert.isOk(isOdd(11)); assert.isOk(isOdd(25)); assert.isOk(isOdd(123)); assert.isOk(isOdd(4567)); assert.isOk(isOdd(2 ** 32 - 1)); }) it("even ones return falsy", () => { assert.isNotOk(isOdd(0)); assert.isNotOk(isOdd(2)); assert.isNotOk(isOdd(4)); assert.isNotOk(isOdd(6)); assert.isNotOk(isOdd(8)); assert.isNotOk(isOdd(10)); assert.isNotOk(isOdd(42)); assert.isNotOk(isOdd(2 ** 32)); }) })
// Since Node 10, we're using Mocha.// You can use `chai` for assertions.- const chai = require("chai");
- const assert = chai.assert;
// Uncomment the following line to disable truncating failure messages for deep equals, do:// chai.config.truncateThreshold = 0;// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.// Uncomment the following to use the old assertions:// const Test = require("@codewars/test-compat");- chai.config.truncateThreshold=0;
describe("Solution", function() {it("should test for something", function() {// Test.assertEquals(1 + 1, 2);// assert.strictEqual(1 + 1, 2);});});- describe("Small numbers", () => {
- it("odd ones return truthy", () => {
- assert.isOk(isOdd(1));
- assert.isOk(isOdd(3));
- assert.isOk(isOdd(5));
- assert.isOk(isOdd(007));
- assert.isOk(isOdd(9));
- assert.isOk(isOdd(11));
- assert.isOk(isOdd(25));
- assert.isOk(isOdd(123));
- assert.isOk(isOdd(4567));
- assert.isOk(isOdd(2 ** 32 - 1));
- })
- it("even ones return falsy", () => {
- assert.isNotOk(isOdd(0));
- assert.isNotOk(isOdd(2));
- assert.isNotOk(isOdd(4));
- assert.isNotOk(isOdd(6));
- assert.isNotOk(isOdd(8));
- assert.isNotOk(isOdd(10));
- assert.isNotOk(isOdd(42));
- assert.isNotOk(isOdd(2 ** 32));
- })
- })