Chuyển số thành số La Mã

Chuyển số thành số La Mã.

Chắc mọi người đều biết về số la mã: I, II, III, IV, V, VI, VII, VIII, IX, X….
Và…

 M = 1,000
 C = 100
 X = 10
 I = 1
 D = 500
 L = 50
 V = 5

Đây là hàm chuyển số thành số La Mã:

// A function to return the Roman Numeral, given an integer
function numberToRoman($num)
{
// Make sure that we only use the integer portion of the value
$n = intval($num);
$result = '';

// Declare a lookup array that we will use to traverse the number:
$lookup = array('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 ($lookup as $roman => $value)
{
// Determine the number of matches
$matches = intval($n / $value);

// Store that many characters
$result .= str_repeat($roman, $matches);

// Substract that from the number
$n = $n % $value;
}

// The Roman numeral should be built, return it
return $result;
}

Popularity: 33% [?]


  1. No comments yet.

  1. No trackbacks yet.

Chọn kiểu gõ: Tự động TELEX VNI Tắt

Bad Behavior has blocked 47 access attempts in the last 7 days.