코딩테스트/C언어

[Level1] 핸드폰 번호 가리기 답안 및 풀이

SRin23 2021. 6. 12. 20:25

◇ 문제 설명

프로그래머스 모바일은 개인정보 보호를 위해 고지서를 보낼 때 고객들의 전화번호의 일부를 가립니다.
전화번호가 문자열 phone_number로 주어졌을 때, 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 *으로 가린 문자열을 리턴하는 함수, solution을 완성해주세요.

 

◇ 제한 조건

  • s는 길이 4 이상, 20이하인 문자열입니다.

 

◇ 입출력 예시

phone_number return
"01033334444" "*******4444"
"027778888" "*****8888"

 

◇ 초기 내용

※ [출처] 프로그래머스-코딩테스트 연습-문제명

※ 초기 내용을 참고하여 문제에 맞는 코드를 작성하세요.

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요.
char* solution(const char* phone_number) {
    // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
    char* answer = (char*)malloc(1);
    return answer;
}

 


◇ 답안

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

char* solution(const char* phone_number) {
    int length = strlen(phone_number);
    char* answer = (char*)malloc(sizeof(char) * length);
    answer = phone_number;
    for(int i = 0; i<length-4; i++){
        answer[i] = '*';
    }
    
    return answer;
}

 

◇ 답안 힌트

    ▶ 간단하게 뒤에서 4자리를 빼고 반복문을 돌려 모두 '*'로 바꾸면 된다.

    ▶ 이를 해결하기 위한 방법은 이 방법 뿐만 아니라 매우 다양하다

 

◇ 답안 풀이

(※ 실행 흐름 순으로 해석됩니다.)

char* solution(const char* phone_number) {

    //매개변수 phone_number의 길이를 변수 length에 저장

    int length = strlen(phone_number);

 

    //sizeof(char) * length만큼 answer에 메모리 할당

    //함수의 반황형이 char포인터 이므로 반환할 값도 char포인터여야한다.
    char* answer = (char*)malloc(sizeof(char) * length);

 

    //answer에 phone_number저장

    //여기에서 이 코드 작성시, phone_number은 값이 바꾸지 않고, 원래 전화번호가 그래도 들어있는 상태     answer = phone_number;

 

    //phone_number의 뒷자리 4개빼고 모두 '*'로 저장

    //주의 문자열 "*"이 아닌 문자 '*'로 저장해야함
    for(int i = 0; i<length-4; i++){
        answer[i] = '*';
    }
    
    return answer;
}

 

◇ 실행결과

핸드폰 번호 가리기 실행결과

 

◇ 출처

https://programmers.co.kr/learn/challenges

 

코딩테스트 연습

기초부터 차근차근, 직접 코드를 작성해 보세요.

programmers.co.kr