罗马数字转换成阿拉伯数字以及递归的简单运用

继上周的阿拉伯数字转换成罗马数字,顺便把罗马数字转阿拉伯数字的也编写一下。

1.题目:

Given a roman numeral, convert it to an integer.

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

题目解析:

这道题主要运用两个规则,其一当左边的罗马数字比右边的罗马数字大时,则相加;反之,则想减。

程序如下:

class Solution {
public:
    int romanToInt(string s) {
        int graph[400];
        graph['I']=1;
        graph['V']=5;
        graph['X']=10;
        graph['L']=50;
        graph['C']=100;
        graph['D']=500;
        graph['M']=1000;
        int sum=graph[s[0]];
        int len=s.length();//注意:在函数定义的s,不能调用函数size()求长度
        for(int i=0;i<len-1;i++)
        {
            if(graph[s[i]]>=graph[s[i+1]])
                 sum+=graph[s[i+1]];
            else
                 sum=sum+graph[s[i+1]]-2*graph[s[i]];
        }
        return sum;
    }
};






这是一道运用递归解决的链表题。

2.题目:

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

题目解析:

此题是有一个循环的,即每两个节点互换,这样我们就可以用到递归,当然也有普通循环解法。

递归程序:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == NULL || head->next == NULL) {
            return head;
        }
        ListNode* stamp = head->next;
        head->next = swapPairs(stamp->next);
        stamp->next = head;
        return stamp;
    }
};

循环程序:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
        ListNode* swapPairs(ListNode* head) {
         ListNode **p = &head, *a, *b;
         while ((a = *p) && (b = a->next)) {
             a->next = b->next;
             b->next = a;
             *p = b;
             p = &(a->next);
          }
          return head;
      }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值