Skip to content

Instantly share code, notes, and snippets.

@mununki
Last active April 18, 2022 18:11
Show Gist options
  • Save mununki/8b5f7dd1b478f4fd2654b29449436cfb to your computer and use it in GitHub Desktop.
Save mununki/8b5f7dd1b478f4fd2654b29449436cfb to your computer and use it in GitHub Desktop.
프로그래머스 코테 - 문자열 정수 더하기
open Belt
// 각 문자열의 가장 뒷 글자끼리 정수로 변환하여 더한다.(a)
// 이전 연산의 결과로 넘어온 값 1 or 0 (b)
// 결과 (c)
// (a + b)가 10 미만인 경우 c 에 prepend 하고, 다음 연산(next)에 0을 넘겨준다.
// (a + b)가 10 이상인 경우 10을 뺀 값을 c에 prepend 하고, 다음 연산(next)에 1을 넘겨준다.
let toArray = s => s->Js.String2.split("")
let solution = (a, b) => {
let rec solutionAux = (xs, ys, idx, next, c) => {
let first = xs->Array.get(idx)->Option.flatMap(Int.fromString)
let second = ys->Array.get(idx)->Option.flatMap(Int.fromString)
let sum = switch (first, second) {
| (Some(f), Some(s)) => f + s + next
| (Some(f), None) => f + next
| (None, Some(s)) => s + next
| (None, None) if next != 0 => next // 유효한 두 개의 정수가 없지만, 올림 숫자가 있는 경우
| (None, None) => -1 // 재귀 종료
}
if sum == -1 {
c
} else if sum < 10 {
solutionAux(xs, ys, idx + 1, 0, sum->Int.toString->Js.String2.concat(c))
} else {
solutionAux(xs, ys, idx + 1, 1, (sum - 10)->Int.toString->Js.String2.concat(c))
}
}
solutionAux(a->toArray->Array.reverse, b->toArray->Array.reverse, 0, 0, "")
}
// 두 문자열의 정수의 합을 문자열로 반환하는 함수
// "1234", "5678" => "6912"
// "1111", "8889" => "10000"
let toArray: string => array<string>
let solution: (string, string) => string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment