Skip to content

Commit 6636df3

Browse files
committed
Resolve "Number of Steps to Reduce a Number in Binary Representation to
One" problem
1 parent 0079cc6 commit 6636df3

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

src/main/java/com/github/dkoval/leetcode/challenge/NumberOfStepsToReduceNumberInBinaryRepresentationToOne.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,32 @@ public int numSteps(String s) {
4545
return steps + carry;
4646
}
4747
}
48+
49+
class NumberOfStepsToReduceNumberInBinaryRepresentationToOneRev2 implements NumberOfStepsToReduceNumberInBinaryRepresentationToOne {
50+
51+
@Override
52+
public int numSteps(String s) {
53+
final var n = s.length();
54+
55+
var count = 0;
56+
var carry = 0;
57+
for (var i = n - 1; i > 0; i--) {
58+
var digit = s.charAt(i) - '0';
59+
digit += carry;
60+
carry = digit / 2;
61+
digit %= 2;
62+
if (digit == 1) {
63+
carry++;
64+
count++;
65+
}
66+
count++;
67+
}
68+
69+
if (carry > 0) {
70+
count++;
71+
}
72+
73+
return count;
74+
}
75+
}
4876
}

src/test/kotlin/com/github/dkoval/leetcode/challenge/NumberOfStepsToReduceNumberInBinaryRepresentationToOneTest.kt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.github.dkoval.leetcode.challenge
22

33
import com.github.dkoval.leetcode.challenge.NumberOfStepsToReduceNumberInBinaryRepresentationToOne.NumberOfStepsToReduceNumberInBinaryRepresentationToOneRev1
4+
import com.github.dkoval.leetcode.challenge.NumberOfStepsToReduceNumberInBinaryRepresentationToOne.NumberOfStepsToReduceNumberInBinaryRepresentationToOneRev2
45
import org.junit.jupiter.api.Assertions.assertEquals
56
import org.junit.jupiter.api.Nested
67
import org.junit.jupiter.api.extension.ExtensionContext
@@ -32,6 +33,16 @@ internal class NumberOfStepsToReduceNumberInBinaryRepresentationToOneTest {
3233
NumberOfStepsToReduceNumberInBinaryRepresentationToOneRev1().test(s, expected)
3334
}
3435
}
36+
37+
@Nested
38+
inner class NumberOfStepsToReduceNumberInBinaryRepresentationToOneRev2Test {
39+
40+
@ParameterizedTest
41+
@ArgumentsSource(InputArgumentsProvider::class)
42+
fun `should return the number of steps to reduce it to 1`(s: String, expected: Int) {
43+
NumberOfStepsToReduceNumberInBinaryRepresentationToOneRev2().test(s, expected)
44+
}
45+
}
3546
}
3647

3748
private fun NumberOfStepsToReduceNumberInBinaryRepresentationToOne.test(s: String, expected: Int) {

0 commit comments

Comments
 (0)