Q. Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
Example.
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) // => returns "(123) 456-7890"
The returned format must be correct in order to complete this challenge.
Don't forget the space after the closing parentheses!
S. 리스트의 서브리스트를 구한 다음 문자열로 바꾸어 문자열 보간법을 이용했다.
String createPhoneNumber(List numbers) {
return "(${numbers.sublist(0, 3).join()}) ${numbers.sublist(3, 6).join()}-${numbers.sublist(6, 10).join()}";
}
+
이렇게 먼저 문자열로 합친 다음에 서브스트링을 이용할 수도 있다. 순서를 바꿔주기만 해도 코드가 간단해지는 경우가 있으니 이런 부분도 연습해봐야겠다.
String createPhoneNumber(List numbers) {
final str = numbers.join();
return "(${str.substring(0, 3)}) ${str.substring(3, 6)}-${str.substring(6, 10)}";
}
'알고리즘 > Codewars' 카테고리의 다른 글
[Codewars] Counting Duplicates (0) | 2024.06.10 |
---|---|
[Codewars] Exes and Ohs (0) | 2024.06.10 |
[Codewars] Find The Parity Outlier (1) | 2024.06.09 |
[Codewars] You're a square! (0) | 2024.06.09 |
[Codewars] Stop gninnipS My sdroW! (1) | 2024.06.08 |