-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Guan Cong
committed
Dec 21, 2022
1 parent
865ae45
commit ccc8056
Showing
2 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
/* | ||
* @lc app=leetcode id=12 lang=csharp | ||
* | ||
* [12] Integer to Roman | ||
*/ | ||
|
||
// @lc code=start | ||
public class Solution { | ||
public string IntToRoman(int num) { | ||
var result = new StringBuilder(); | ||
var map = new Dictionary<int, string> | ||
{ | ||
{ 1000, "M" }, | ||
{ 900, "CM" }, | ||
{ 500, "D" }, | ||
{ 400, "CD" }, | ||
{ 100, "C" }, | ||
{ 90, "XC" }, | ||
{ 50, "L" }, | ||
{ 40, "XL" }, | ||
{ 10, "X" }, | ||
{ 9, "IX" }, | ||
{ 5, "V" }, | ||
{ 4, "IV" }, | ||
{ 1, "I" }, | ||
}; | ||
while (num > 0) { | ||
foreach (var key in map) { | ||
if (num >= key.Key) { | ||
result.Append(key.Value); | ||
num -= key.Key; | ||
break; | ||
} | ||
} | ||
} | ||
|
||
return result.ToString(); | ||
|
||
} | ||
} | ||
// @lc code=end | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
/* | ||
* @lc app=leetcode id=8 lang=csharp | ||
* | ||
* [8] String to Integer (atoi) | ||
*/ | ||
|
||
// @lc code=start | ||
public class Solution { | ||
public int MyAtoi(string s) { | ||
int i = 0; // index | ||
int sign = 1; // sign | ||
int result = 0; | ||
if (s.Length == 0) return 0; // empty string | ||
while (i < s.Length && s[i] == ' ') i++; // skip white spaces | ||
if (i < s.Length && (s[i] == '+' || s[i] == '-')) { // check sign | ||
sign = (s[i++] == '+') ? 1 : -1; // skip sign | ||
} | ||
while (i < s.Length && s[i] >= '0' && s[i] <= '9') { // check number | ||
if (result > Int32.MaxValue / 10 || (result == Int32.MaxValue / 10 && s[i] - '0' > 7)) { // check overflow | ||
return (sign == 1) ? Int32.MaxValue : Int32.MinValue; // return max or min | ||
} | ||
result = result * 10 + (s[i++] - '0'); // calculate result | ||
} | ||
return result * sign; | ||
} | ||
} | ||
// @lc code=end | ||
|