博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode]Integer to Roman AND ROman to Integer
阅读量:6704 次
发布时间:2019-06-25

本文共 1465 字,大约阅读时间需要 4 分钟。

hot3.png

Given an integer, convert it to a roman numeral.

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

[java]
  1. public class Solution { 
  2.     public String intToRoman(int num) { 
  3.         int[] number = {
    1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };   
  4.         String[] str = {
    "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };  
  5.         StringBuilder sb=new StringBuilder(); 
  6.         for(int i = 0;i<number.length;i++){ 
  7.             while(number[i]<=num){ 
  8.                 num-=number[i]; 
  9.                 sb.append(str[i]); 
  10.             } 
  11.         } 
  12.         return sb.toString(); 
  13.     } 
public class Solution {    public String intToRoman(int num) {        int[] number = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };          String[] str = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };         StringBuilder sb=new StringBuilder();        for(int i = 0;i

Given a roman numeral, convert it to an integer.

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

[java]
  1. public class Solution { 
  2.     public int romanToInt(String s) { 
  3.         int[] number = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; 
  4.         String[] str = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", 
  5.                 "V", "IV", "I" }; 
  6.         int it = 0, res = 0; 
  7.         for (int i = 0; i < str.length; i++) { 
  8.             for (int j = 2; j >= 1; j--) { 
  9.                 if(it==s.length()-1) j=1; 
  10.                 while (s.substring(it, it + j).equals(str[i])) { 
  11.                     it+=j; 
  12.                     if(it==s.length()-1) j=1; 
  13.                      
  14.                     res+=number[i]; 
  15.                     if(it>=s.length()){ 
  16.                         return res; 
  17.                     } 
  18.                 } 
  19.             } 
  20.         } 
  21.         return res; 
  22.     } 

转载于:https://my.oschina.net/pangzhuzhu/blog/318064

你可能感兴趣的文章
删除所有的binlog后打不开
查看>>
SATA 250GB*8 RAID数据恢复过程记录
查看>>
装了正版XP的感受
查看>>
Lync Server 2010企业版系列PART5:生成拓扑
查看>>
多年后,才知道自己是多么的无知
查看>>
说说我眼中的IT界加班文化
查看>>
Cocos2d-x 3.0标签类Label
查看>>
【C++】定义自己的String类
查看>>
利用模块添加系统调用(不重新编译内核)
查看>>
解决Lightmap在PC上与ios和Android上表现不同的问题
查看>>
冬至潮汕谚语
查看>>
UNITY中有Timer
查看>>
Introducing Holographic Emulation
查看>>
字体大小
查看>>
angularjs 模块化
查看>>
PMBOK项目管理PMI主义\IPMA概述
查看>>
解决Azure中COULD NOT LOAD FILE OR ASSEMBLY问题
查看>>
Windows Azure HandBook (8) Azure性能测试(1)
查看>>
优化事务处理
查看>>
iphone:Core Data:Where does a Managed Object Context Come From?
查看>>