Notice
Recent Posts
Recent Comments
Tags
more
Today
Total
«   2025/06   »
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 30
관리 메뉴

SW 꿈나무

[Level 1][C] 자연수 뒤집어 배열로 만들기 본문

Algorithm/Programmers

[Level 1][C] 자연수 뒤집어 배열로 만들기

현식 :) 2020. 3. 26. 18:18
  • 문제

    자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해 주세요.

    예들 들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다.

  • 제한 조건

    n은 10,000,000,000 이하인 자연수입니다.

  • Example

    Input 1 : 12345
    Output 1 : [5,4,3,2,1]
  • Code

    #include <stdio.h>
    #include <stdbool.h>
    #include <stdlib.h>
    
    int* solution(long long n) {
    
        long long digit=n;            // digit 선언 및 n 대입
        int count=1;                  // count 선언 및 1 대입 -> 아래 조건문에서 10이하의 수는 count 되지 않기 때문
        for(int i=0;i<10;i++) {       // 제한 조건인 의 승수만큼 반복
            if(digit/10>0) {          // digit / 10 이 0보다 크면
                digit/=10;            // digit = digit / 10
                count+=1;             // count = count + 1
            }
        }   
        int* answer = (int*)malloc(sizeof(int)*count);    // answer 에 count 수만큼 메모리 동적 할당
    
        for(int i=0;i<count;i++) {    // count 수만큼 반복
            answer[i]=n%10;           // answer[i] 자리에 n % 10 대입
            n=n/10;                   // n = n / 10
        } 
        return answer;                // answer 반환
    }
Comments