罗马数字和阿拉伯数字之间的转换

问题描述:把我们常见的阿拉伯数字转化为罗马数字的形式。
拓展:两种形式的相互转换。
思路:将阿拉伯数字拆分为能够被罗马数字整除的形式(比如100、500等),再整合到一起,然后替换字符为我们需要的形式(比如IIII=>IV,VIV=>IX等等)。再使用键值对形式的数组,在实现阿拉伯数字转罗马数字之后,交换键值,就能实现反向转换了。

function solution($number) {
  $roman = array(
    'M' => 1000,
    'D' => 500,
    'C' => 100,
    'L' => 50,
    'X' => 10,
    'V' => 5,
    'I' => 1
  );
  //从大到小遍历,拆分阿拉伯数字
  foreach($roman as $key=>$item) {
    if($number / $item > 0) {
      $int = intval($number / $item);
      $number -= $int * $item;
      for($i=0;$i<$int;$i++) {
        $str .= $key;
      }
    }
  }
  return str_replace(['IIII','XXXX','CCCC','VIV','LXL','DCD'],['IV','XL','CD','IX','XC','CM'],$str);
}

我们发现,如4、9、40、90这种转换为罗马数字之后还需要做额外的替换,那为何不直接将其添加到数组里面去呢?

function solution(int $number)
 {
 $roman = [
   'M' => 1000,
   'CM' => 900,
   'D' => 500,
   'CD' => 400,
   'C' => 100,
   'XC' => 90,
   'L' => 50,
   'XL' => 40,
   'X' => 10,
   'IX' => 9,
   'V' => 5,
   'IV' => 4,
   'I' => 1
 ];
 foreach($roman as $key=>$item){
  //使用str_repeat代替循环
  $str.= str_repeat($key,intval($number/$item));
  $number %= $value;
 }
 return $str;
}
//个人感觉这种思想方式也很简单灵巧
function solution($n)
 {
    $M = ["","M","MM","MMM"];
    $C = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"];
    $X = ["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"];
    $I = ["","I","II","III","IV","V","VI","VII","VIII","IX"];
    return $M[$n/1000].$C[($n % 1000)/100].$X[($n % 100)/10].$I[($n % 10)];
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注