Skip to main content

Command Palette

Search for a command to run...

[LeetCode] 1404. Number of Steps to Reduce a Number in Binary Representation to One

Updated
3 min read

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 to 1 under 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 1 to 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: 0

Constraints:

  • 1 <= s.length <= 500

  • s consists of characters '0' or '1'

  • s[0] == '1'

문제 분석

bit 연산의 특징을 이용해야할 것으로 보입니다.

  • 비트 연산의 경우 자리 수 1개를 지우면 나누기 2를 한 수치와 동일

  • 홀수일 경우 1의 자리수가 1, 짝수 일 경우 일의 자리 수가 0

따라서 다음과 같은 순서도를 가진다고 하면 문제를 풀 수 있을 것입니다.

  1. 일의 자리 수가 1인 경우, 1의 더함

  2. 일의 자리 수가 2인 경우, 나누기 2를 함

  3. 만약 현재 문자열이 1이 아니라면 1을 반복한다

  4. 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을 더해주는 작업에서 시간을 추가적으로 소요되었습니다.

2 views

More from this blog

카프카 입문 시리즈 2편: 토픽, 파티션, 오프셋

이 글은 Apache Kafka 입문 시리즈의 두 번째 글입니다. 1편에서 살펴본 구성 요소들 위에서, 메시지가 실제로 어떤 구조로 저장되고 관리되는지 알아보겠습니다. 1편을 마치며 세 가지 질문을 남겼습니다. 메시지는 브로커 안에서 어떤 구조로 저장될까? 토픽과 파티션은 정확히 무엇이고, 왜 필요할까? 컨슈머의 오프셋은 어떻게 동작할까? 이번 편에서 이 질문들에 하나씩 답하겠습니다. Topic: 메시지의 논리적 분류 토픽(Topic)은...

Mar 19, 202612 min read7

Java GC의 진화 — Serial에서 Generational ZGC까지

Java가 약속한 것 중 하나는 "메모리는 내가 관리할게"였다. C/C++ 개발자들이 malloc과 free로 메모리와 씨름하던 시절, Java는 Garbage Collector(GC)라는 자동 메모리 관리자를 들고 나왔다. 개발자는 객체를 만들기만 하면 되고, 치우는 건 GC가 알아서 한다. 하지만 "알아서"라는 말에는 대가가 있었다. GC가 동작하는 동안 애플리케이션이 멈추는 것이다. 이 멈춤을 Stop-The-World(STW) 일시 정지...

Mar 16, 20269 min read1

Spring의 3대 철학 — DI, AOP, PSA가 만드는 코드의 품격

Spring을 처음 배울 때, 나는 어노테이션 수집가였다. @Autowired를 붙이면 객체가 알아서 들어오고, @Transactional을 붙이면 트랜잭션이 알아서 관리되고, @Cacheable을 붙이면 캐시가 알아서 동작했다. "알아서"라는 말 뒤에 숨은 원리를 몰랐다. 그냥 마법이라고 생각했다. 그러다 문제가 생겼다. @Transactional을 붙였는데 롤백이 안 됐다. 같은 클래스 안에서 메서드를 호출했기 때문이었다. 원인을 찾는 데 ...

Mar 16, 202611 min read9

Spring Boot Docker 이미지, 한 줄 한 줄에 담긴 고민

처음 Spring Boot 애플리케이션을 Docker로 배포했을 때, Dockerfile은 딱 세 줄이었다. FROM openjdk:17 COPY build/libs/app.jar app.jar ENTRYPOINT ["java", "-jar", "app.jar"] 동작은 했다. 하지만 이미지 크기는 700MB를 넘겼고, 코드 한 줄 고칠 때마다 전체 JAR를 다시 빌드해야 했다. 프로덕션에 올릴 때는 root 권한으로 실행되고 있었다. "동작...

Mar 16, 202610 min read4

끄적끄적 테크 블로그

32 posts

물류 회사에 다니고 있는 개발자 블로그입니다. 개발을 너무 좋아해서 정신없이 작업하다가 중간에 끄적거리며 내용들을 몇개 적어봅니다 ㅎㅎ

[LeetCode] 1404. Number of Steps to Reduce a Number in Binary Representation to One