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 }
  • 相关阅读:
    数据库+mysql
    网络并发项目
    网络编程 IO模型
    并发编程之死锁、进程池、协程
    类的使用
    面向对象—多态,反射
    面向对象-三大特性
    继承与派生
    面向对象
    模块进阶(二)
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4234658.html
Copyright © 2011-2022 走看看