https://leetcode.com/problems/integer-to-roman/submissions/
* 12.php
<?php
class Solution {
// a[0] > a[1] > a[2] ...
private static function indexLessThan($a, $ans, $start=0) {
$n = count($a);
for ($i = $start; $i < $n; $i++) {
if ($a[$i] <= $ans) {
return $i;
}
}
return -1;
}
/**
* @param Integer $num
* @return String
*/
public function intToRoman($num) {
$a = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
$b = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L','XL','X','IX','V', 'IV', 'I'];
$r = [];
while (($i = self::indexLessThan($a, $num, 0)) >= 0) {
$num -= $a[$i];
array_push($r, $b[$i]);
}
$s = "";
foreach ($r as $t) {
$s .= $t;
}
return $s;
}
}
* 测试代码
$s = new Solution();
// 27 XXVII
// 1994 MCMXCIV
$cases = [3, 12, 27, 4, 19, 58, 1994];
foreach ($cases as $case) {
printf("%d => %s\n", $case, $s->intToRoman($case));
}
运行结果
$ php 12.php
3 => III
12 => XII
27 => XXVII
4 => IV
19 => XIX
58 => LVIII
1994 => MCMXCIV
有不必要的数组造成内存开销,直接拼接字符串即可。
而且数字总是从大往下匹配,所以只需要一次循环。
<?php
class Solution {
/**
* @param Integer $num
* @return String
*/
public function intToRoman($num) {
$a = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
$b = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L','XL','X','IX','V', 'IV', 'I'];
$s = "";
$i = 0;
while ($num > 0) {
if ($num >= $a[$i]) {
$num -= $a[$i];
$s .= $b[$i];
} else {
$i += 1;
}
}
return $s;
}
}
$s = new Solution();
// 27 XXVII
// 1994 MCMXCIV
$cases = [3, 12, 27, 4, 19, 58, 1994];
foreach ($cases as $case) {
printf("%d => %s\n", $case, $s->intToRoman($case));
}
https://leetcode.com/problems/integer-to-roman/submissions/
用Java写:
package com.leetcode.integerToRoman;
public class Solution {
public String intToRoman(int num) {
int[] a = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] b = {"M", "CM", "D", "CD", "C","XC","L","XL","X","IX","V","IV", "I"};
StringBuilder sb = new StringBuilder();
int i = 0;
while (num > 0) {
if (num >= a[i]) {
num -= a[i];
sb.append(b[i]);
} else {
i++;
}
}
return sb.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution s = new Solution();
int[] cases = {3, 12, 27, 4, 19, 58, 1994};
for (int i = 0; i < cases.length; i++) {
System.out.printf("%d => %s\n", cases[i], s.intToRoman(cases[i]));
}
}
}
相关文章: Leetcode#13. Roman to Integer
来源:CSDN
作者:fareast_mzh
链接:https://blog.csdn.net/fareast_mzh/article/details/103928100