首页 > 其他 > 详细

Leetcode题解(四)

时间:2015-12-01 21:10:51      阅读:260      评论:0      收藏:0      [点我收藏+]

12/13、Integer to Roman/Roman to Integer 

题目

技术分享

罗马数字规则:

符号 I V X L C D M
数字 1 5 10 50 100 500 1000

代码如下:

 

 1 class Solution {
 2 public:
 3     string intToRoman(int num) {
 4         string str;    
 5         string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};    
 6         int value[]=    {1000,900,500,400, 100, 90,  50, 40,  10, 9,   5,  4,   1};   
 7         for(int i=0;num!=0;++i)  
 8         {  
 9             while(num>=value[i])  
10             {  
11                 num-=value[i];  
12                 str+=symbol[i];  
13             }  
14         }  
15         return str;  
16 
17     }
18 };

举一反三,如果是将罗马数字转换为整数呢。思路是一样。参考代码如下:

 1 class Solution {
 2 public:
 3     int romanToInt(string s) {
 4         int ret = toNumber(s[0]);
 5         for (int i = 1; i < s.length(); i++) {
 6             if (toNumber(s[i - 1]) < toNumber(s[i])) {
 7                 ret += toNumber(s[i]) - 2 * toNumber(s[i - 1]);
 8             } else {
 9                 ret += toNumber(s[i]);
10             }
11         }
12         return ret;
13     }
14     
15     int toNumber(char ch) {
16         switch (ch) {
17             case I: return 1;
18             case V: return 5;
19             case X: return 10;
20             case L: return 50;
21             case C: return 100;
22             case D: return 500;
23             case M: return 1000;
24         }
25         return 0;
26     }
27 };

 

-------------------------------------------------------------------------------------------------分割线----------------------------------------------------------------------------

14、Longest Common Prefix

题目

技术分享

这道题目比较简单,参考代码如下:

 1 class Solution {
 2 public:
 3     string longestCommonPrefix(vector<string> &strs) {
 4         int length = strs.size();
 5         string result="";
 6         int index=0,i;
 7         char temp;
 8         bool flag=true;
 9         if(0 == length)
10             return "";
11         while(flag)
12         {
13             temp=strs[0][index];
14 
15             for (i=0;i<length;i++)
16             {
17                 if (index>=strs[i].length() ||strs[i][index] != temp)
18                 {
19                     flag=false;
20                     break;
21                 }
22 
23             }
24             if(i==length)
25                 result += temp;
26             index++;
27 
28         }
29         return result;
30     }
31 };

 

Leetcode题解(四)

原文:http://www.cnblogs.com/LCCRNblog/p/5011249.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!