leetcode-1-basic

 

leetcode-algorithm

1. Two Sum

解法:循环,试呗。。简单粗暴。。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        //vector<int> temp = nums;
        int i;
        int j;
        vector<int> result(2);
        bool flag = false;
        for (i = 0 ; i != nums.size()-1; i++) {
            for (j = i+1; j != nums.size(); j++) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    flag = true;
                    break;
                    }
                }
                if (flag == true)
                break;
            }
        return result;
    }
};

 

7. Reverse Integer 

class Solution {
public:
    int reverse(int x) {
        long newNum;
        newNum = 0;
        while(x != 0) {
            // overflow has to be handled
            newNum = newNum * 10 + x % 10;
            if(newNum > INT_MAX || newNum < INT_MIN)
                return 0;
            x = x / 10;
            }
        return newNum;
    }
};

9. Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

sol: transform into string and compare within string

class Solution {
public:
    bool isPalindrome(int x) {
        string s = std::to_string(x);
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            if (s[i] != s[j])
                return false;
                i++;
                j--;
            }
        return true;
    }
};

13. Roman to Integer

class Solution {
public:
    int myFunc(char c) {
        int data = 0;
        switch (c) {
            case 'I':
                data = 1;
                break;
            case 'V':
                data = 5;
                break;
            case 'X':
                data = 10;
                break;
            case 'L':
                data = 50;
                break;
            case 'C':
                data = 100;
                break;
            case 'D':
                data = 500;
                break;
            case 'M':
                data = 1000;
                break;
        }
        return data;
    }
    int romanToInt(string s) {
        int result = 0;
        int i;
        int pre;
        int cur;
        result = myFunc(s[0]);
        if (s.length() == 1)
           return result;
        for (i = 1; i < s.length(); i++) {
            pre = myFunc(s[i-1]);
            cur = myFunc(s[i]);
            if (pre >= cur)
              result += cur;
            else
              result = result - 2 * pre + cur;
        }
        return result;
    }
};

 

posted @ 2017-02-23 08:57  陆离可  阅读(142)  评论(0编辑  收藏  举报