LeetCode - Integer to Roman
来源:互联网 发布:阿里云备案解释 编辑:程序博客网 时间:2024/05/16 15:02
https://leetcode.com/problems/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-3,4,5-8,9分别处理。public class Solution { public String intToRoman(int num) { //I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、M(1000) int rank = 1000; int index = 6; StringBuilder rst = new StringBuilder(); char[] roman = {'I', 'V', 'X', 'L', 'C', 'D', 'M'}; while(rank > 0){ int val = num/rank; num = num % rank; if(val>=1 && val<=3){ while(val>0){ rst.append(roman[index]); val--; } } if(val == 4){ rst.append(roman[index]); rst.append(roman[index+1]); } if(val>=5 && val<=8){ val -=5; rst.append(roman[index+1]); while(val>0){ rst.append(roman[index]); val--; } } if(val==9){ rst.append(roman[index]); rst.append(roman[index+2]); } rank /=10; index-=2; } return rst.toString(); }}
其实更直接的方法是,把所有情况都列出来,然后直接用switch来返回相应的值,每位都有9中情况,千位3种,一共30种。
0 0
- LeetCode Roman to Integer && Integer to Roman
- 【leetcode】Roman to Integer | Integer to Roman
- Leetcode - "Roman to Integer" & "Integer to Roman"
- LeetCode:Roman to Integer,Integer to Roman
- LeetCode Integer to Roman & Roman to Integer
- leetcode - roman to integer & integer to roman
- LeetCode:Roman to Integer
- LeetCode: Integer to Roman
- LeetCode: Roman to Integer
- LeetCode Integer to Roman
- LeetCode: Integer to Roman
- LeetCode : Roman to Integer
- [Leetcode] Roman to Integer
- [Leetcode] Integer to Roman
- Leetcode: Integer to Roman
- Leetcode: Roman to Integer
- LeetCode Integer to Roman
- 【leetcode】Roman to Integer
- [csu oj] 1548: Design road(三分)
- 使用cscope
- 逞咨俸钨汛弦舷擦渍诼
- Erlang处理汉字的相关博文【收集整理】
- LeetCode: Buy and Sell Stock相关问题合集
- LeetCode - Integer to Roman
- 2月16日--3月29日(共50小时,剩3820小时)
- Java中的equals和hashCode方法详解
- 创业干货:在众说纷纭中找到前进的方向
- openpam
- 蚈蒄螀肅芁莆螆袁肁荿袂羀
- 薆蚂罿膂薆螄螂肈薅薄羈肄
- 莅蚁薃膃莈螇螂羂芀莀羁袂
- 肃莁薃羇膆膃葿羆袅荿莅羅