문제 풀기/C#

27. 핸드폰 번호 가리기

kagan-draca 2025. 1. 16. 14:28

 

풀이 1)

 

문제가 어려워 보이지만 이전 문제들을 풀면서 배운 함수들을 잘 활용하면 쉽게 해결할 수 있다.

 

Select() 함수의 콜백 함수로 (element, index)를 매개 변수로 선택 후,

 

phone_number.Length - 4 > index 보다 크면 "*"로,

 

아니면, element로 출력 선택해준다.

 

이를 ToArray()로 char[] 형 배열로 만든 후,

 

string.Join("",)으로 string 타입 즉, 문자열로 바꿔주면 간단하게 해결할 수 있었다. 

 

using System;
using System.Linq;

public class Solution {
    public string solution(string phone_number) 
    {
        return string.Join("",phone_number.Select((element, index) => phone_number.Length - 4 > index ? '*' : element).ToArray());
    }
}

 

풀이 2) 반복문을 활용해서 index와 phone_number.Length - 4 길이 비교하기

 

using System;
using System.Linq;

public class Solution {
    public string solution(string phone_number) 
    {
        string result = "";
        for(int i = 0; i < phone_number.Length; i++)
        {
            result += phone_number.Length - 4 > i ? "*" : phone_number[i].ToString(); 
        }
        return result;
    }
}

 

 

풀이 2)가 풀이 1) 보다 수행시간이 짧은 이유를 추측해보면

 

phone_number 변수가 string인데 Select로 반복문이 실행될 것이고,

이후 ToArray()로 char[]의 배열로 형변환이 이뤄졌으며,

string.Join()으로 char[] 배열이 string 타입으로 다시 한 번 반복문을 통해 다 합쳐질 것이라

 

더 많은 수행시간을 요구하는 것으로 보인다.