13. Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

这题可以直接从string的后端往前端搜索。因为正常情况下,越往前,高位的数越大,当前一位数小的话,只会是4或者9的情况。所以高位大则相加,高位小,则减去。字符和数值之间的映射可以hash table 来表示。代码如下。

class Solution {
public:
    /*1    I 
      5    V
      10   X   
      50   L
      100  C
      500  D
      1000 M*/
    int romanToInt(string s) {
        string refchar = "MDCLXVI";
        vector<int> refnum = {1000, 500, 100, 50, 10, 5, 1};
        unordered_map<char, int> hash;

        for (int i = 0; i < 7; i++) {
            hash[refchar[i]] = refnum[i];
        }
        int len = s.size();
        int ans = hash[s[len - 1]];
        for (int i = s.size() - 2; i >= 0; i--) {
            if (hash[s[i]] >= hash[s[i + 1]]) {
                ans += hash[s[i]];
            } 
            else {
                ans -= hash[s[i]];
            }
        }
        return ans;
    }
};

其实也可以从前往后检索,后一个比前面的小就直接加上,否则就加上后一个减去两倍的前一个。
要想提高速度,可以避免用hash table,自己写一个简单的映射函数,如下:

inline int c2n(char c) {  
  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;  
    default: return 0;  
  }  
}  
int romanToInt(string s) {  
  // Start typing your C/C++ solution below  
  // DO NOT write int main() function  
  int result=0;  
  for(int i =0; i< s.size(); i++)  
  {  
    if(i>0&& c2n(s[i]) > c2n(s[i-1]))  
    {  
      result +=(c2n(s[i]) - 2*c2n(s[i-1]));  
    }  
    else  
    {  
      result += c2n(s[i]);  
    }  
  }  
  return result;  
}  

注:inline function的标识是为了加快代码的执行速度,让编译器识别到这个经常使用的简单函数并作特别处理。

Why to use –
In many places we create the functions for small work/functionality which contain simple and less number of executable instruction. Imagine their calling overhead each time they are being called by callers.
When a normal function call instruction is encountered, the program stores the memory address of the instructions immediately following the function call statement, loads the function being called into the memory, copies argument values, jumps to the memory location of the called function, executes the function codes, stores the return value of the function, and then jumps back to the address of the instruction that was saved just before executing the called function. Too much run time overhead.
The C++ inline function provides an alternative. With inline keyword, the compiler replaces the function call statement with the function code itself (process called expansion) and then compiles the entire code. Thus, with inline functions, the compiler does not have to jump to another location to execute the function, and then jump back as the code of the called function is already available to the calling program.
With below pros, cons and performance analysis, you will be able to understand the “why” for inline keyword
Pros :-
1. It speeds up your program by avoiding function calling overhead.
2. It save overhead of variables push/pop on the stack, when function calling happens.
3. It save overhead of return call from a function.
4. It increases locality of reference by utilizing instruction cache.
5. By marking it as inline, you can put a function definition in a header file (i.e. it can be included in multiple compilation unit, without the linker complaining)

Cons :-
1. It increases the executable size due to code expansion.
2. C++ inlining is resolved at compile time. Which means if you change the code of the inlined function, you would need to recompile all the code using it to make sure it will be updated
3. When used in a header, it makes your header file larger with information which users don’t care.
4. As mentioned above it increases the executable size, which may cause thrashing in memory. More number of page fault bringing down your program performance.
5. Sometimes not useful for example in embedded system where large executable size is not preferred at all due to memory constraints.

When to use -
Function can be made as inline as per programmer need. Some useful recommendation are mentioned below-
1. Use inline function when performance is needed.
2. Use inline function over macros.
3. Prefer to use inline keyword outside the class with the function definition to hide implementation details.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值