From af9de3f83bf21634cb9a6c1ff902099e51a11cf7 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 29 May 2024 23:41:59 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB1404.=20Number=20of=20Steps?= =?UTF-8?q?=20to=20Reduce=20a=20Number=20in=20Binary=20Representation=20to?= =?UTF-8?q?=20One=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...a-number-in-binary-representation-to-one.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 go/number-of-steps-to-reduce-a-number-in-binary-representation-to-one.go diff --git a/go/number-of-steps-to-reduce-a-number-in-binary-representation-to-one.go b/go/number-of-steps-to-reduce-a-number-in-binary-representation-to-one.go new file mode 100644 index 0000000..29fac25 --- /dev/null +++ b/go/number-of-steps-to-reduce-a-number-in-binary-representation-to-one.go @@ -0,0 +1,18 @@ +package number_of_steps_to_reduce_a_number_in_binary_representation_to_one + +func numSteps(s string) int { + steps := 0 + carry := 0 + for i := len(s) - 1; i > 0; i-- { + bit := int(s[i]) + carry + + if bit%2 == 1 { + steps += 2 + carry = 1 + } else { + steps += 1 + } + } + + return steps + carry +}