https://school.programmers.co.kr/learn/courses/30/lessons/148653#
구현 아이디어 5분 구현 27분
storey를 string으로 변환해 각 자리의 값에 따라 처리를 했다. 핵심은 지금 판단하려는 값이 5 이상일 때 앞 자리가 5 이상이라면 5(혹은 50, 500...)을 더하고 그렇지 않다면 빼야한다.
#include <string>
#include <vector>
using namespace std;
int solution(int storey) {
int answer = 0;
string str_storey = to_string(storey);
int tmp = storey;
int mul = 1;
for(int i = str_storey.size() - 1; i >= 0; --i)
{
// 처음에는 1의 자리일 것.
int cur_num = str_storey[i] - '0';
if(cur_num == 0) continue;
// 변환을 위한 mul 변수 세팅.
mul = 1;
for(int j = 0; j < str_storey.size() - i - 1; ++j) mul *= 10;
if(cur_num == 5 && i > 0)
{
int next_num = str_storey[i - 1] - '0';
if(next_num >= 5)
tmp = tmp + (5 * mul);
else
tmp = tmp - (5 * mul);
answer += 5;
}
else if(cur_num > 5)
{
tmp = tmp + ((10 - cur_num) * mul);
answer += (10 - cur_num);
}
// i가 0일 때 5인 경우가 있을 수 있음. 따라서 <=.(테케 9번)
else if(cur_num <= 5)
{
tmp = tmp - (cur_num * mul);
answer += cur_num;
}
str_storey = to_string(tmp);
// 자릿수가 늘어날 경우를 대비해 ++i.
++i;
}
//printf("%s ", str_storey.c_str());
return answer;
}