Leetcode Note: Go - Number of Steps to Reduce a Number to Zero

Number of Steps to Reduce a Number to Zero - LeetCode
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/

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

回答

Go 100% time and 100% space | log(n) - Number of Steps to Reduce a Number to Zero - LeetCode
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/solutions/1621952/go-100-time-and-100-space-log-n/

func numberOfSteps(num int) int {
	if num == 0 {
		return 0
	}

	result := 0
	for num > 0 {
		if num&1 == 1 {
			result += 2
		} else {
			result += 1
		}

		num >>= 1
	}

	return result - 1
}