Leetcode 13. Roman to Integer C语言

简介:
1
2
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

罗马数字与整数互转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
int  getInt( char  c){
     int  temp;
     switch (c){
         case  'I' : return  1;
         case  'V' : return  5;
         case  'X' : return  10;
         case  'L' : return  50;
         case  'C' : return  100;
         case  'D' : return  500;
         case  'M' : return  1000;
         }
         return  0;
}
int  romanToInt( char * s) {
     int  temp;
     int  sum=getInt(s[0]);
     for ( int  i=1;i< strlen (s);i++){
         if (getInt(s[i-1])<getInt(s[i])){
             sum+=getInt(s[i]);
             sum-=2*getInt(s[i-1]);
             // printf("%d-->%d\n",getInt(s[i-1]),getInt(s[i]));
             
         } else {
             sum+=getInt(s[i]);
             // printf("{%d}",getInt(s[i]));
         }
         
     }
     return  sum;
}

PS:一开始以为就是从左到右求和比较。。。。。。。。。。。。结果发现错误了。做这道题首先搞明白罗马数字规则。。。。。。。。。。。。。。。。现在也不知道。挨个比较,左边比右边大的话直接加,左边比右边小的话先加再减两倍。。。。。。。。。。。。。。。。。。。。。。。。

2、第一次在Leetcode额外定义函数,要写在已给函数的前面。。。。。。。。。。。。。。。。。。



本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1884076

相关文章
|
5月前
|
算法 C语言 容器
从C语言到C++_18(stack和queue的常用函数+相关练习)力扣(上)
从C语言到C++_18(stack和queue的常用函数+相关练习)力扣
41 0
|
5月前
|
存储 C语言
Leetcode—— 删除排序数组中的重复项——C语言
Leetcode—— 删除排序数组中的重复项——C语言
|
5月前
|
算法 C语言
Leetcode----旋转数组 ------C语言篇
Leetcode----旋转数组 ------C语言篇
|
5月前
|
C语言
LeetCode---消失的数字---C语言实现
LeetCode---消失的数字---C语言实现
|
5月前
|
算法 C语言 容器
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145(下)
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145
54 7
|
5月前
|
存储 算法 C语言
从C语言到C++_39(C++笔试面试题)next_permutation刷力扣
从C语言到C++_39(C++笔试面试题)next_permutation刷力扣
45 5
|
5月前
|
存储 C语言 容器
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别(下)
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别
40 1
|
5月前
|
存储 C语言 容器
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别(中)
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别
43 1
|
5月前
|
存储 自然语言处理 C语言
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别(上)
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别
51 1
|
5月前
|
C语言
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145(中)
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145
46 1