Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,943 questions

55,787 answers

573 users

How to find the Nth set bit in a 32‑bit integer with Scala

1 Answer

0 votes
import java.lang.Integer

object FindNthSetBit32 {

  // Count trailing zeros using Java's built-in method
  def countTrailingZeros(x: Int): Int =
    Integer.numberOfTrailingZeros(x)

  // Find the Nth set bit in a 32-bit integer
  def findNthSetBit32(x0: Int, n0: Int): Int = {
    var x = x0
    var n = n0

    while (x != 0) {
      val index = countTrailingZeros(x)

      n -= 1
      if (n == 0)
        return 1 << index

      x &= (x - 1)
    }

    0
  }

  // Convert to padded 32-bit binary string
  def toBinary32(x: Int): String = {
    val s = Integer.toBinaryString(x)
    "0" * (32 - s.length) + s
  }

  def main(args: Array[String]): Unit = {
    val value: Int = 0b00001101001101101100100010100000
    val n: Int = 4

    val result: Int = findNthSetBit32(value, n)

    println("Input value:  " + toBinary32(value))
    println("N = " + n)
    println("Result mask:  " + toBinary32(result))
  }
}


/*
run:

Input value:  00001101001101101100100010100000
N = 4
Result mask:  00000000000000000100000000000000

*/

 



answered Jul 25 by avibootz
...