프로그래머스 모바일은 개인정보 보호를 위해 고지서를 보낼 때 고객들의 전화번호의 일부를 가립니다.
전화번호가 문자열 phone_number로 주어졌을 때, 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 *으로 가린 문자열을 리턴하는 함수, solution을 완성해주세요.
문자열 가공 시 메모리 절약을 위해 StringBuffer 객체를 사용했다. 루프를 거꾸로 돌며 4자리가 저장되고 나면 가려야 하는 남은 문자열 만큼 *를 저장해 주었다. 버퍼 객체의 경우 reverse() 메서드를 가지고 있어 return이 쉬웠다.
class Solution {
public String solution(String phone_number) {
StringBuffer answer = new StringBuffer();
for(int i=phone_number.length() - 1; i>=0; i--){
if(answer.toString().length() < 4){
answer.append(phone_number.charAt(i));
}else{
answer.append("*");
}
}
return answer.reverse().toString();
}
}
