leetcode刷题记录
Posted zhangjin1120
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode刷题记录相关的知识,希望对你有一定的参考价值。
LeetCode刷题目录
leetcode刷题7.整数反转求余算法
示例1:
输入:x = 123
输出:321
示例 2:
输入:x = -123
输出:-321
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
class Solution
public int reverse(int x)
if (x == 0||x==Integer.MIN_VALUE)
return 0;
String num = String.valueOf(x);
boolean isNagi = false;
if (num.contains("-"))
isNagi = true;
x = -x;
String resultStr = "";
while (x / 10 != 0 || x % 10 != 0)
resultStr = resultStr + x % 10;
x = x / 10;
if (isNagi)
resultStr = "-" + resultStr;
if (resultStr.isEmpty())
return 0;
long result = Long.valueOf(resultStr);
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)
return 0;
return (int)result;
leetcode刷题13.罗马数字转整数HashMap+ArrayList
示例 1:
输入: s = “III”
输出: 3
示例 2:
输入: s = “IV”
输出: 4
示例 3:
输入: s = “IX”
输出: 9
示例 4:
输入: s = “LVIII”
输出: 58
解释: L = 50, V= 5, III = 3.
示例 5:
输入: s = “MCMXCIV”
输出: 1994
解释: M = 1000, CM = 900, XC = 90, IV = 4.
class Solution
public static int romanToInt(String s)
int result = 0;
HashMap<String, Integer> charIntMap = new HashMap<>();
charIntMap.put("I", 1);
charIntMap.put("V", 5);
charIntMap.put("X", 10);
charIntMap.put("L", 50);
charIntMap.put("C", 100);
charIntMap.put("D", 500);
charIntMap.put("M", 1000);
charIntMap.put("IV", 4);
charIntMap.put("IX", 9);
charIntMap.put("XL", 40);
charIntMap.put("XC", 90);
charIntMap.put("CD", 400);
charIntMap.put("CM", 900);
//拆分
char[] charGroup = s.toCharArray();
for (int i = 0; i < charGroup.length; i++)
//1. I IV IX
//2. V
//3. X XL XC
//4. L
//5. C CD CM
//6. D
//7. M
char current=charGroup[i];
String key=" ";
if (i + 1 < charGroup.length)
char next = charGroup[i + 1];
if (current == 'I')
if (next == 'V' || next == 'X')
key="" + current + next;
i++;
else
key=("" + current);
else if (current == 'X')
if (next == 'L' || next == 'C')
key=("" + current + next);
i++;
else
key=("" + current);
else if (current == 'C')
if (next == 'D' || next == 'M')
key=("" + current + next);
i++;
else
key=("" + current);
else
key=("" + current);
else
key=("" + current);
//累加
result += charIntMap.get(key);
return result;
以上是关于leetcode刷题记录的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode刷题记录[python]——283 Move Zeroes