본문 바로가기
연습장

Create Phone Number

by anothel 2022. 2. 15.

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(int[10]{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!

 

Solution

#include <string>

std::string getNumber(const int& startIndex, const int& count, const int arr[10]) {
  std::string sNumber;

  for(int i = startIndex; i < startIndex + count; i++) {
    sNumber += std::to_string(arr[i]);
  }

  return sNumber;
}

std::string createPhoneNumber(const int arr [10]){
  std::string sReturn;  

  sReturn += "(";
  sReturn += getNumber(0, 3, arr);
  sReturn += ") ";
  sReturn += getNumber(3, 3, arr);
  sReturn += "-";
  sReturn += getNumber(6, 4, arr);
  
  return sReturn;
}

 

남의 코드

#include <string>

std::string createPhoneNumber(const int arr [10]){
  char buf[15];
  snprintf(buf, sizeof(buf), "(%d%d%d) %d%d%d-%d%d%d%d%d", arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6], arr[7], arr[8], arr[9]);
  return buf;
}
std::string createPhoneNumber(const int digits[10]) {
  std::string res = "(...) ...-....";
  for (unsigned is = 0, id = 0; is < res.length(); is++)
    if (res[is] == '.')
      res[is] = '0' + digits[id++];
  return res;
}

 

후기

숫자가 담긴 배열을 받아서 전화번호 형식으로 출력하는 문제이다. 이 문제를 푼 다른 사람들의 코드를 보면 나 이렇게도 풀어봤어요~하듯 참 다양하게들 풀었다. 아무래도 어차피 정해진 형식이라면 함수로 빼고 뭘 할 필요도 없이 그냥 snprintf로 한 번에 처리해주는 게 맞는 것 같다.

 

(url: https://www.codewars.com/kata/525f50e3b73515a6db000b83)

 

728x90

'연습장' 카테고리의 다른 글

초콜릿 자르기 - 2163  (0) 2022.02.16
A+B - 7 - 11021  (0) 2022.02.16
Row of the odd triangle  (0) 2022.02.14
피보나치 함수 - 1003  (1) 2022.02.13
터렛 - 1002  (0) 2022.02.12