Leetcode 题目摘录

Easy

  1. Palindrome Number
    Given an integer x, return true if x is palindrome integer.
    An integer is a palindrome when it reads the same backward as forward.
    For example, 121 is a palindrome while 123 is not.
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
bool isPalindrome(int x) {
if(x<0|| (x!=0 &&x%10==0)) return false; //ends with 0
int sum=0;
while(x>sum)
{
sum = sum*10+x%10;
x = x/10;
}
return (x==sum)||(x==sum/10); //when x contains only one digit
}
};
  1. Roman to Integer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int romanToInt(string s) 
{
unordered_map<char, int> T = { { 'I' , 1 },
{ 'V' , 5 },
{ 'X' , 10 },
{ 'L' , 50 },
{ 'C' , 100 },
{ 'D' , 500 },
{ 'M' , 1000 } };

int sum = T[s.back()];
for (int i = s.length() - 2; i >= 0; --i)
{
if (T[s[i]] < T[s[i + 1]])
{
sum -= T[s[i]];
}
else
{
sum += T[s[i]];
}
}

return sum;
}

Powered by Hexo

Copyright © 2013 - 2023 骸骨长廊 All Rights Reserved.

UV : | PV :