[LeetCode] 1404. Number of Steps to Reduce a Number in Binary Representation to One
Link : 1404. Number of Steps to Reduce a Number in Binary Representation to One
문제 설명
Given the binary representation of an integer as a string
s, return the number of steps to reduce it to1under the following rules:
If the current number is even, you have to divide it by
2.If the current number is odd, you have to add
1to it.It is guaranteed that you can always reach one for all test cases.
Example 1:
Input: s = "1101" Output: 6 Explanation: "1101" corressponds to number 13 in their decimal representation. Step 1) 13 is odd, add 1 and obtain 14. Step 2) 14 is even, divide by 2 and obtain 7. Step 3) 7 is odd, add 1 and obtain 8. Step 4) 8 is even, divide by 2 and obtain 4. Step 5) 4 is even, divide by 2 and obtain 2. Step 6) 2 is even, divide by 2 and obtain 1.Example 2:
Input: s = "10" Output: 1 Explanation: "10" corresponds to number 2 in their decimal representation. Step 1) 2 is even, divide by 2 and obtain 1.Example 3:
Input: s = "1" Output: 0Constraints:
1 <= s.length <= 500
sconsists of characters '0' or '1'
s[0] == '1'
문제 분석
bit 연산의 특징을 이용해야할 것으로 보입니다.
비트 연산의 경우 자리 수 1개를 지우면 나누기 2를 한 수치와 동일
홀수일 경우 1의 자리수가 1, 짝수 일 경우 일의 자리 수가 0
따라서 다음과 같은 순서도를 가진다고 하면 문제를 풀 수 있을 것입니다.
일의 자리 수가 1인 경우, 1의 더함
일의 자리 수가 2인 경우, 나누기 2를 함
만약 현재 문자열이 1이 아니라면 1을 반복한다
1~3을 순회한 횟수 반환
문제 해결
class Solution {
fun numSteps(s: String): Int {
var steps = 0
var cur = s
while (cur != "1") {
if (cur.last() == '1') {
cur = addOne(cur)
steps += 1
} else {
cur = cur.dropLast(1)
steps++
}
}
return steps
}
fun addOne(cur: String): String {
val idx = cur.indexOfLast { it == '0' }
return if (idx == -1) {
'1' + "0".repeat(cur.length)
} else {
cur.substring(0, idx) + '1' + "0".repeat(cur.length - idx - 1)
}
}
}
느낀점
문자열 연산 자체는 이미 알고 있었지만 숫자 1을 더해주는 작업에서 시간을 추가적으로 소요되었습니다.

