7th Contest of Newbies A, UVa-12397 : Roman Numerals

問題概要

1~3999の整数が与えられる。ローマ数字で書くのにマッチ棒が何本必要か求める問題。

解法

各桁毎に置き換えるだけ。もうすこしDRY原則を意識して書くべきだった。

acceptされたコード

#include <cstdio>
#include <cstring>
using namespace std;

int N;

bool init(){
	return scanf("%d", &N) != EOF;
}

int solve(){
	int thousand = N / 1000;
	int hundred = (N / 100) % 10;
	int ten = (N / 10) % 10;
	int one = N % 10;

	int ans = 0;
	//1000
	ans += thousand * 4;

	//100
	if(hundred <= 3){
		ans += 2 * hundred;
	}
	else if(hundred == 4){
		ans += 2 + 3;
	}
	else if(hundred <= 8){
		ans += 3 + 2*(hundred - 5);
	}
	else if(hundred == 9){
		ans += 2 + 4;
	}

	//10
	if(ten <= 3){
		ans += 2 * ten;
	}
	else if(ten == 4){
		ans += 2 + 2;
	}
	else if(ten <= 8){
		ans += 2 + 2 * (ten - 5);
	}
	else if(ten == 9){
		ans += 2 + 2;
	}

	//1
	if(one <= 3){
		ans += one;
	}
	else if(one == 4){
		ans += 3;
	}
	else if(one <= 8){
		ans += 2 + (one - 5);
	}
	else if(one == 9){
		ans += 3;
	}

	return ans;
}

int main(){
	while(init()){
		printf("%d\n", solve());
	}

	return 0;
}