Thursday, February 23, 2023
HomeSoftware EngineeringHow one can Discover Subsequent Increased Quantity with Similar Bits in Golang

# How one can Discover Subsequent Increased Quantity with Similar Bits in Golang

## The problem#

Discover the subsequent greater quantity (int) with identical ‘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 unhealthy 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)
``````

Possibility 1:

``````bundle resolution
func NextHigher(x int) int  rightOnesPattern
return subsequent

``````

Possibility 2:

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

Possibility 3:

``````bundle 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#

``````bundle solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Kata", func() {
It("Primary checks", 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