상세 컨텐츠

본문 제목

[Programmers] Lv.2 이진 변환 반복하기 (Go)

Development/Algorithm

by thisisnew 2022. 11. 4. 15:45

본문

반응형

https://school.programmers.co.kr/learn/courses/30/lessons/70129

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제 설명

0과 1로 이루어진 어떤 문자열 x에 대한 이진 변환을 다음과 같이 정의합니다.

x의 모든 0을 제거합니다.
x의 길이를 c라고 하면, x를 "c를 2진법으로 표현한 문자열"로 바꿉니다.
예를 들어, x = "0111010"이라면, x에 이진 변환을 가하면 x = "0111010" -> "1111" -> "100" 이 됩니다.

0과 1로 이루어진 문자열 s가 매개변수로 주어집니다. s가 "1"이 될 때까지 계속해서 s에 이진 변환을 가했을 때, 이진 변환의 횟수와 변환 과정에서 제거된 모든 0의 개수를 각각 배열에 담아 return 하도록 solution 함수를 완성해주세요.

 

제한사항

  • s의 길이는 1 이상 150,000 이하입니다.
  • s에는 '1'이 최소 하나 이상 포함되어 있습니다.

Solution

import(
	"strconv"
	"strings"
)

const DestinationNumber = "1"

func solution(s string) []int {
	var cnt int
	var removeZeros int

	for s != DestinationNumber {
		r, c := countAndRemoveZeros(s)
		s = convertDecimalToBinary(len(r))
		removeZeros += c
		cnt++
	}

	return []int{cnt, removeZeros}
}

func countAndRemoveZeros(s string) (string, int) {

	var result strings.Builder
	var cnt int

	for _, r := range s {

		if r == '0' {
			cnt++
			continue
		}

		result.WriteRune(r)
	}

	return result.String(), cnt
}

func convertDecimalToBinary(l int) string {
	return strconv.FormatInt(int64(l), 2)
}

반응형

관련글 더보기

댓글 영역