Posted on by Kalkicode
Code Bit Logic

Count total set bits in all numbers from 1 to n in node js

Js program for Count total set bits in all numbers from 1 to n. Here more solutions.

/*
   Node JS program for
   Count total set bits in all numbers from 1 to n
*/
class BitCount
{
	// Returns number of set bits of given number
	countSetBit(num)
	{
		var x = num;
		x = x - ((x >>> 1) & 1431655765);
		x = (x & 858993459) + ((x >>> 2) & 858993459);
		x = (x + (x >>> 4)) & 252645135;
		x = x + (x >>> 8);
		x = x + (x >>> 16);
		x = x & 63;
		// Number of set bit
		return x;
	}
	// Handles the request of counting the number 
	// of active bits from 1 to n
	countSetBits(n)
	{
		if (n < 0)
		{
			return;
		}
		var result = 0;
		// Execute loop from 1 to n
		for (var i = 1; i <= n; ++i)
		{
			// Add set bits
			result += this.countSetBit(i);
		}
		console.log("\n Active Bit from (1 to " + n + ")");
		// Display result
		console.log(" Output : " + result);
	}
}

function main()
{
	var task = new BitCount();
	// Test A
	// number(1-7)  Setbit
	// ----------------
	// 1  = 0001      1
	// 2  = 0010      1
	// 3  = 0011      2   
	// 4  = 0100      1
	// 5  = 0101      2
	// 6  = 0110      2 
	// 7  = 0111      3 
	// --------------------
	//                12
	task.countSetBits(7);
	// Test B
	// number(1-10)  Setbit
	// ----------------
	// 1  = 0001      1
	// 2  = 0010      1
	// 3  = 0011      2   
	// 4  = 0100      1
	// 5  = 0101      2
	// 6  = 0110      2 
	// 7  = 0111      3 
	// 8  = 1000      1
	// 9  = 1001      2 
	// 10  = 1010     2 
	// --------------------
	//                17
	task.countSetBits(10);
}
// Start program execution
main();

Output

 Active Bit from (1 to 7)
 Output : 12

 Active Bit from (1 to 10)
 Output : 17

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment