9. Roman to Integer
来源:互联网 发布:小米禁用软件设置 编辑:程序博客网 时间:2024/06/14 03:36
Description:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Conversion Rule:
- 1.相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;
- 2.小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;
- 3.小的数字(限于 I、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;
- 4.正常使用时、连写的数字重复不得超过三次;
Solution:
1. How to split the String and express them to Integer ?
(1) String.toCharArray()
// return an array.
or
String.charAt(int i)
// according to the traversal, get the each Char.
(2) switch(String.char(int i)){
case 'M' :
num[I] = 1000;
break;
or
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
2. How to calculate the result ?
If the left character's value is smaller than the right one, we should add the left one.
If the left character's value is larger than the right one or this is the last character, we should subtract the left one.
Therefore, we can use the top s.length-1 value to compare, and leave the last one to add only.
codes
import java.util.HashMap;public class RomantoInteger { public static int romanToInt(String s){ int[] nums = new int[s.length()]; for (int i = 0; i < s.length(); i++) { switch (s.charAt(i)) { case 'M': nums[i] = 1000; break; case 'D': nums[i] = 500; break; case 'C': nums[i] = 100; break; case 'L': nums[i] = 50; break; case 'X': nums[i] = 10; break; case 'V': nums[i] = 5; break; case 'I': nums[i] = 1; break; } } int sum = 0; for (int i = 0; i < nums.length-1; i++){ if (nums[i] >= nums[i+1]){ sum += nums[i]; } else { sum -= nums[i]; } } return sum + nums[nums.length-1]; }}
Lesson learned:
1. String function
2. switch
- 9. Roman to Integer
- Integer to Roman & Roman to Integer
- Integer to Roman & Roman to Integer
- 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
- Integer to Roman and Roman to Integer
- LeetCode Integer to Roman & Roman to Integer
- Roman to Integer/Integer to Roman
- leetcode - roman to integer & integer to roman
- "Roman to Integer" and "Integer to Roman"
- Roman to Integer &&Integer to Roman
- Roman to Integer and Integer to Roman
- Roman to Integer/Integer to Roman
- LeetCode:Roman to Integer
- LeetCode: Integer to Roman
- LeetCode: Roman to Integer
- Java
- OpenCV计算机视觉入门案例
- 【转载】多态
- 【shell】tr
- 【shell】sort uniq
- 9. Roman to Integer
- 惊呆!即使禁用定位,谷歌也在通过安卓系统收集用户定位信息
- 拥抱你的AI新同事,虽然最后你可能被抛弃——欢迎来到AI协同工作纪元
- 维密超模何穗时尚大片来袭,vivo携手时尚芭莎直击维密盛况
- 赛可达9-10月横评报告:腾讯电脑管家再居第一
- 梅格·惠特曼宣布将辞去惠普企业CEO职务
- 今日头条:去年10亿扶植短视频 今年10亿沉淀深度问答用户
- 独家 | 小 i 机器人朱频频:融资4.5亿,但 AI 生意和地推一样“苦逼”
- 中国经济的数字化转型,正吸引人才奔向北上广 | 雷报第44期