首页 > 代码库 > Leetcode-Integer to Roman
Leetcode-Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Solution:
1 public class Solution { 2 public String intToRoman(int num) { 3 String[] symbol = new String[]{"I","V","X","L","C","D","M"}; 4 int[] val = new int[]{1,5,10,50,100,500,1000}; 5 6 String res = ""; 7 int index = 6; 8 int symNum = num/val[index]; 9 int left = num%val[index];10 if (symNum>0)11 for (int i=0;i<symNum;i++) res += symbol[index];12 index -=2;13 while (left!=0){14 symNum = left/val[index];15 left = left%val[index]; 16 if (symNum==0){17 index-=2;18 continue; 19 } else if (symNum==9) res += symbol[index]+symbol[index+2];20 else if (symNum==4) res += symbol[index]+symbol[index+1];21 else if (symNum<4) 22 for (int i=0;i<symNum;i++) res += symbol[index];23 else {24 res += symbol[index+1];25 for (int i=0;i<symNum-5;i++) res += symbol[index];26 }27 index -= 2;28 29 }30 31 return res;32 }33 }
Leetcode-Integer to Roman
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。