Tuesday, April 23, 2024
HomeSoftware EngineeringThe right way to Discover Subsequent Increased Quantity with Similar Bits in...

The right way to Discover Subsequent Increased Quantity with Similar Bits in Golang


The problem

Discover the subsequent greater quantity (int) with similar ‘1’- Bits.

I.e. as a lot 1 bits as earlier than and output subsequent greater than enter. Enter is at all times an int in between 1 and 1«30 (inclusive). No dangerous circumstances or particular tips…

Examples:

Enter: 129  => Output: 130 (10000001 => 10000010)
Enter: 127 => Output: 191 (01111111 => 10111111)
Enter: 1 => Output: 2 (01 => 10)
Enter: 323423 => Output: 323439 (1001110111101011111 => 1001110111101101111)

The answer in Golang

Choice 1:

package deal resolution
func NextHigher(x int) int  rightOnesPattern
  return subsequent

Choice 2:

package deal resolution
import (
  "strconv"
  "strings"
)
func NextHigher(n int) int {
  for i := n+1 ; i > 0 ; i ++ {
    if strings.Rely(strconv.FormatInt(int64(n), 2) , "1") == strings.Rely(strconv.FormatInt(int64(i), 2) , "1") { return i } }
  return 0
}

Choice 3:

package deal resolution
import (
  "math/bits"
)
func NextHigher(n int) int {
  bcount := bits.OnesCount32(uint32(n))
  for x := uint32(n+1); ;x++ {
    if bits.OnesCount32(x) == bcount {
      return int(x)
    }
  }
  return 0
}

Take a look at circumstances to validate our resolution

package deal solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("Kata", func() {
    It("Primary exams", func() {
        Count on(NextHigher(128)).To(Equal(256))
        Count on(NextHigher(1)).To(Equal(2))
        Count on(NextHigher(1022)).To(Equal(1279))
        Count on(NextHigher(127)).To(Equal(191))
        Count on(NextHigher(1253343)).To(Equal(1253359))
    })
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments