Leetcode Note: Go - Binary Gap

Binary Gap - LeetCode
https://leetcode.com/problems/binary-gap/

  • Go 言語で取り組んだメモ

所感

  • int n が渡されるので 2進数 に変換して 1 の値の最大距離を int で return する

回答

Binary Gap - LeetCode
https://leetcode.com/problems/binary-gap/solution/

golang bitwise shift - LeetCode Discuss
https://leetcode.com/problems/binary-gap/discuss/1364757/golang-bitwise-shift

func binaryGap(n int) int {
	curDistance, maxDistance := 0, 0
	seenOne := false
	for ; n > 0; n >>= 1 {
		if n & 1 == 1 {
			if curDistance > maxDistance {
				maxDistance = curDistance
			}
			curDistance = 1
			seenOne = true
		} else if seenOne {
			curDistance++
		}
	}
	return maxDistance
}