Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Count Set Bits in Kotlin #7305

Merged
merged 2 commits into from
May 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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