From b0fe972cff5838dc8938cdfff582c419fb0e166c Mon Sep 17 00:00:00 2001 From: Kirubanand Date: Tue, 25 May 2021 09:25:16 +0530 Subject: [PATCH 1/2] CountSetBits.kt file added in Kotlin/BitManipulation/ and modified README.md --- Kotlin/BitManipulation/CountSetBits.kt | 54 ++++++++++++++++++++++++++ Kotlin/Readme.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 Kotlin/BitManipulation/CountSetBits.kt diff --git a/Kotlin/BitManipulation/CountSetBits.kt b/Kotlin/BitManipulation/CountSetBits.kt new file mode 100644 index 0000000000..db6e9369bc --- /dev/null +++ b/Kotlin/BitManipulation/CountSetBits.kt @@ -0,0 +1,54 @@ +import java.util.Scanner + +/* + +A Kotlin Program to find the XOR of 1 to N. + +*/ + +fun main(args: Array ) { + + val input = Scanner(System.`in`) + + // Get the required input from the user + println("Enter the number to count no. of set bits in it : ") + val n: Int = input.nextInt() + + val result = countSetBits(n) + println("The no. of set bits is : $result") + +} + +// Defining a function that will take an number and return the count of set bits in it +fun countSetBits(n: Int): Int { + var count = 0 + var num = n + + // In every iteration, the last set bit of the number is made unset + // Therefore, the count of set bits, would be the no. of times the last set bit can be removed until zero occurs + while(num != 0) { + num = num and (num - 1); + count++ + } + + return count +} + +/* +Sample Test Cases: + + Test case 1: + Enter the number to count no. of set bits in it : + 10453 + The no. of set bits is : 7 + + Test Case 2: + Enter the number to count no. of set bits in it : + 1023 + The no. of set bits is : 10 +*/ + +/* + Time complexity: O(1) + Space complexity: O(1) +*/ \ No newline at end of file diff --git a/Kotlin/Readme.md b/Kotlin/Readme.md index bd70b95b60..1073d4a267 100644 --- a/Kotlin/Readme.md +++ b/Kotlin/Readme.md @@ -15,6 +15,7 @@ - [Single Number I](BitManipulation/SingleNumber_I.kt) - [Power Of Two](BitManipulation/PowerOfTwo.kt) - [XOR from 1 to N](BitManipulation/XORFromOneToN.kt) +- [Count Set Bits](BitManipulation/CountSetBits.kt) ## Competitive Programming From e0f50bad8df6fd200a2136fcdd60562c214890a1 Mon Sep 17 00:00:00 2001 From: Kirubanand Date: Tue, 25 May 2021 09:27:43 +0530 Subject: [PATCH 2/2] Changed Time Complexity in CountSetBits.kt file --- Kotlin/BitManipulation/CountSetBits.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Kotlin/BitManipulation/CountSetBits.kt b/Kotlin/BitManipulation/CountSetBits.kt index db6e9369bc..20878a4dca 100644 --- a/Kotlin/BitManipulation/CountSetBits.kt +++ b/Kotlin/BitManipulation/CountSetBits.kt @@ -49,6 +49,6 @@ Sample Test Cases: */ /* - Time complexity: O(1) + Time complexity: O(No. of Set Bits) Space complexity: O(1) -*/ \ No newline at end of file +*/