zoukankan      html  css  js  c++  java
  • Integer to Roman

    Given an integer, convert it to a roman numeral.

    Input is guaranteed to be within the range from 1 to 3999.

     1 public class Solution {
     2     public String intToRoman(int num) {
     3         String romans[][] = new String[][]{
     4                 {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
     5                 {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
     6                 {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
     7                 {"", "M", "MM", "MMM",}
     8         };
     9         String result = "";
    10         int index = 0;
    11         while(num != 0){
    12             String temp = romans[index][num % 10];
    13             result = temp + result;
    14             index++;
    15             num = num / 10;
    16         }//while
    17         
    18         return result;
    19     }
    20 }

     下面是使用的贪心算法,每次减去最大的

     1 public class Solution {
     2     public String intToRoman(int num) {
     3         int array_int[] = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
     4         String array_string[] = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
     5         
     6         StringBuffer sb = new StringBuffer();
     7         for(int i = 0; i < array_int.length; i++){
     8             while(num >= array_int[i]){
     9                 num -= array_int[i];
    10                 sb.append(array_string[i]);
    11             }//while
    12         }//for
    13         
    14         return sb.toString();
    15     }
    16 }
  • 相关阅读:
    超级楼梯
    超级楼梯
    母牛的故事
    母牛的故事
    蟠桃记
    蟠桃记
    Children’s Queue
    Children’s Queue
    http://202.194.116.8/webapps/portal/frameset.jsp?tab_id=_2_1&url=%2fwebapps%2fblackboard%2fexecute%2
    Matlab位运算笔记
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4234658.html
Copyright © 2011-2022 走看看