ys memos

Blog

Leetcode 12 Integer to Roman


leetcode

2020/05/27


与えられた整数int numをローマ数字を表す文字列に変換する問題

<例>
3 -> "III"
4 -> "IV"
9 -> "IX"
58 -> "LVIII"
1994 -> "MCMXCIV"

string intToRoman(int num) {
  auto digitConverter = [](char c1, char c5, char c10, int num){
    string part;
    switch(num){
      case 3: part += c1;
        [[fallthough]]
      case 2: part += c1;
        [[fallthough]]
      case 1: part += c1;
        return part;
      case 4: part += c1;
        [[fallthough]]
      case 5: part += c5;
        return part;
      case 8: part += c1;
        [[fallthough]]
      case 7: part += c1;
        [[fallthough]]
      case 6: part += c1;
        return c5 + part;
      case 9:
        part += c1;
        part += c10;
        return part;
      default:
        return part;
    }
  };
  string roman;
  roman += digitConverter('M',' ',' ',num/1000%10);
  roman += digitConverter('C','D','M',num/100%10);
  roman += digitConverter('X','L','C',num/10%10);
  roman += digitConverter('I','V','X',num%10);
  return roman;
}

digitConverter()は、桁をローマ数字に変換するラムダ式。引数には、各桁を表すローマ字が必要。 [[fallthough]]を活用しながら、switch-caseを用いて条件分岐をした。

string intToRoman(int num) {
  auto digitConverter = [](char c1, char c5, char c10, int num){
    string part;
    switch(num){
      case 3: part += c1;
        [[fallthough]]
      case 2: part += c1;
        [[fallthough]]
      case 1: part += c1;
        return part;
      case 4: part += c1;
        [[fallthough]]
      case 5: part += c5;
        return part;
      case 8: part += c1;
        [[fallthough]]
      case 7: part += c1;
        [[fallthough]]
      case 6: part += c1;
        return c5 + part;
      case 9:
        part += c1;
        part += c10;
        return part;
      default:
        return part;
    }
  };

高い桁から順にローマ数字に変換していく。 num/1000%10は1000の位の数字を抜き出す。

  string roman;
  roman += digitConverter('M',' ',' ',num/1000%10);
  roman += digitConverter('C','D','M',num/100%10);
  roman += digitConverter('X','L','C',num/10%10);
  roman += digitConverter('I','V','X',num%10);
  return roman;
}

関連タグを探す