Skip to content

Commit

Permalink
Merge pull request #7305 from kiruba-r11/feature-1
Browse files Browse the repository at this point in the history
Added Count Set Bits in Kotlin
  • Loading branch information
siddharth25pandey committed May 31, 2021
2 parents 987a49c + e0f50ba commit 473eb34
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
54 changes: 54 additions & 0 deletions Kotlin/BitManipulation/CountSetBits.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import java.util.Scanner

/*
A Kotlin Program to find the XOR of 1 to N.
*/

fun main(args: Array <String>) {

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(No. of Set Bits)
Space complexity: O(1)
*/
1 change: 1 addition & 0 deletions Kotlin/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 473eb34

Please sign in to comment.