Excel Sheet Column Number && Roman to Integer && Integer to Roman && Reverse Integer && Palindrome N

Excel Sheet Column Number

我的思路:

1、进制转换。

代码如下:

    int titleToNumber(string s) {
        int ans = 0;
        
        for (int i = 0; i < s.size(); i++) 
            ans = ans * 26 + s[i] - 64; 

        return ans;
    }

Roman to Integer

我的思路:

1、类似进制转换。

class Solution {
public:
    int romanToInt(string s) {
        Roman r[7] = {{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
        int ans = 0;
        
        for (int i = 0; i < s.size(); i++) {
            int j;
            for (j = 0; j < 7 && r[j].c != s[i]; j++)
                ;
            if (r[j].c == 'I' && (s[i + 1] == 'V' || s[i + 1] == 'X') || r[j].c == 'X' && (s[i + 1] == 'L' || s[i + 1] == 'C') || r[j].c == 'C' && (s[i + 1] == 'D' || s[i + 1] == 'M'))
                ans -= r[j].num;
            else
                ans += r[j].num;
        }
        return ans;
    }
private:
    typedef struct {
        char    c;
        int     num;
    }Roman;
};

Integer to Roman

我的思路:

1、将罗马数字转换成整数,注意4和9的时候的转换。

代码如下:

class Solution {
public:
    string intToRoman(int num) {
        string  s;
        int     i = 0, j = 6;
        while (num) {
    		i   = num / r[j].num;
            num -= r[j].num * i;
    		if ((r[j].c == 'V' || r[j].c == 'L' ||  r[j].c == 'D') && (num / r[j - 1].num == 4) && i == 1) {
    			num -= r[j - 1].num * 4;
    			s.push_back(r[j - 1].c);
    			s.push_back(r[j + 1].c);
    		}
    		else if (i == 4) {
                s.push_back(r[j].c);
                s.push_back(r[j + 1].c);
            }
            else
                while (i--)
                    s.push_back(r[j].c);
    		j--;
        }
        return s;
    }
private:
    typedef struct {
        char    c;
        int     num;
    }Roman;
    Roman r[7] = {{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
};


别人思路:

1、类似打表,这个方法在C和指针这本书中有提到过,讲的是16进制到10进制的转换。

别人代码


Reverse Integer

我的思路:

1、10进制倒转和2进制倒转是有差别的。

    int reverse(int x) {
        long long int ans = 0;
        while (x) {
            ans = ans * 10 + x % 10; 
            x = x / 10;
        }
        ans = (ans > 2147483647 || ans < -2147483647) ? 0 : ans;
        return ans;
    }

Palindrome Number

我的思路:

1、将上面那题的结果直接拿来比对就行。

代码1:

    bool isPalindrome(int x) {
        if (x < 0)
            return false;
        long long int ans = 0;
        int temp = x;
        while (x) {
            ans = ans * 10 + x % 10; 
            x = x / 10;
        }
        if (ans == temp)
            return true;
        else
            return false;
    }
2、另一种方法。

3、本来是想从头尾两边比对,如果不对,立马返回。还没想到算了。

代码2:





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值