leetcode 13. Roman to Integer
来源:互联网 发布:万网域名证书生成 编辑:程序博客网 时间:2024/05/31 05:27
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question.
看到这个题首先百度了一下罗马数字:
I
V
X
L
C
D
M
1
5
10
50
100
500
1000
- 1、相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;
- 2、小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;
- 小的数字(限于 I、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;
- 3、正常使用时、连写的数字重复不得超过三次;
- 4、在一个数的上面画一条横线、表示这个数扩大 1000 倍。
- 有两条须注意掌握:
- 1、基本数字 Ⅰ、X 、C 中的任何一个、自身连用构成数目、或者放在大数的右边连用构成数目、都不能超过三个;放在大数的左边只能用一个;
- 2、不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目、只能使用一个;
解题思路:将上面的7个字符存放在一个常量字符数组中,public static final char[] ch = {'I','V','X','L','C','D','M'};
下标为奇数的对应的阿拉伯数字为 Math.pow(10, j/2)
下标为偶数的对应的阿拉伯数字为Math.pow(10, (j - 1)/2)
首先将输入的字符串的每个字符转为对应的阿拉伯数字并用一个int类型的数组存储,然后挨个判断每个数是否比其后的一个数小,如果小就减去这个数,否则加上这个数。
for(int i = 0;i < len - 1;i++){
if(inum[i] >= inum[i + 1]){
sum += inum[i];
}else{
sum -= inum[i];
}
}
if(inum[i] >= inum[i + 1]){
sum += inum[i];
}else{
sum -= inum[i];
}
}
最后求出结果。
代码如下所示:
public static final char[] ch = {'I','V','X','L','C','D','M'};
public static int RomantoInt(String s){
int sum = 0;
int len = s.length();
int[] inum = new int[len];
char[] ch3 = s.toCharArray();
int k = 0;
for(int i = 0;i < len;i++){
for(int j = 0;j < 7;j++){
if(ch3[i] == ch[j]){
if(j % 2 == 0){
inum[k++] = (int)Math.pow(10, j/2);
}else{
inum[k++] = (int)Math.pow(10, (j - 1)/2);
}
}
}
}
for(int i = 0;i < len - 1;i++){
if(inum[i] >= inum[i + 1]){
sum += inum[i];
}else{
sum -= inum[i];
}
}
sum += inum[len-1];
return sum;
}
int sum = 0;
int len = s.length();
int[] inum = new int[len];
char[] ch3 = s.toCharArray();
int k = 0;
for(int i = 0;i < len;i++){
for(int j = 0;j < 7;j++){
if(ch3[i] == ch[j]){
if(j % 2 == 0){
inum[k++] = (int)Math.pow(10, j/2);
}else{
inum[k++] = (int)Math.pow(10, (j - 1)/2);
}
}
}
}
for(int i = 0;i < len - 1;i++){
if(inum[i] >= inum[i + 1]){
sum += inum[i];
}else{
sum -= inum[i];
}
}
sum += inum[len-1];
return sum;
}
0 0
- LeetCode 13. Roman to Integer
- [LeetCode]13.Roman to Integer
- LeetCode --- 13. Roman to Integer
- [Leetcode] 13. Roman to Integer
- [leetcode] 13.Roman to Integer
- leetcode 13. Roman to Integer
- leetcode 13. Roman to Integer
- LeetCode 13. Roman to Integer
- [LeetCode]13. Roman to Integer
- Leetcode 13. Roman to Integer
- leetcode 13. Roman to Integer
- leetcode 13. Roman to Integer
- LeetCode *** 13. Roman to Integer
- LeetCode 13. Roman to Integer
- LeetCode 13. Roman to Integer
- 【LeetCode】13. Roman to Integer
- Leetcode 13. Roman to Integer
- LeetCode 13. Roman to Integer
- 140.Fragment实现程序锁未加锁模块
- 进制转换
- 读书笔记《Effective C++》条款03:尽可能使用const
- myeclipse的problem报错,工程出现了一个感叹号
- easyui datagrid combobox多选第一个时最前面会多加“,”逗号
- leetcode 13. Roman to Integer
- raw binary文件探秘
- webstrom注册方法 不用下载插件
- 试探用法
- 5.文件操作 --- 系统调用
- 【C语言】(windows.h)MessageBox函数
- 湖大程序设计题5
- Android 实现拨打电话
- Uva11059—最大乘积