我的思路:
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进制的转换。
我的思路:
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: