분해합_2231번

[Python, Go] 백준 2231번 풀이

분해합

  • 자연수 N의 생성자를 찾기 위해 1부터 N이전까지의 수를 모두 탐색한다.

    • N이 1일때는 생성자가 존재하지 않으므로 0을 출력한다.

    • i 를 키워나가면서 가장 작은 생성자를 찾으면 멈추고, N-1까지 탐색했을 때 결과값이 존재하지 않다면 0을 출력한다.

    • i 의 각 자리수를 sum에 더해줄때, 각 자리수를 for문으로 돌려서 더해주었음. —> 10으로 나누고 나머지를 사용하는 방법도있다.

  • Python 풀이

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    n = int(input())

    if n==1:
    print(0)

    for i in range(1,n):
    sum = i
    for j in str(i):
    sum += int(j)
    if sum == n:
    print(i)
    break
    elif i == n-1 :
    print(0)
  • Go 풀이

    • Python과 같은 방법을 사용했는데 Go에서는 int를 스트링으로 바꿔주기 위해 “strconv”를 사용하였다.

    • strconv.Itoa를 통해 int를 string으로 변환

    • strconv.ParseInt를 통해 string을 int로 바꿔주었다.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      package main

      import (
      "fmt"
      "strconv"
      )

      func main() {
      var n int
      fmt.Scanf("%d", &n)

      if n == 1 {
      fmt.Printf("%d", 0)
      }

      for i := 1; i < n; i++ {
      sum := i
      for _, j := range strconv.Itoa(sum) {
      k, _ := strconv.ParseInt(string(j), 10, 8)
      sum += int(k)
      }
      if sum == n {
      fmt.Printf("%d", i)
      break
      } else if i == n-1 {
      fmt.Printf("%d", 0)
      }
      }
      }

Full Code

Full Code - Python

Full Code - Go

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×