Skip to content

Commit

Permalink
feat: added two sol
Browse files Browse the repository at this point in the history
  • Loading branch information
Guan Cong committed Dec 21, 2022
1 parent 865ae45 commit ccc8056
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
42 changes: 42 additions & 0 deletions csharp/12.integer-to-roman.cs
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

28 changes: 28 additions & 0 deletions csharp/8.string-to-integer-atoi.cs
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

0 comments on commit ccc8056

Please sign in to comment.