-
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.
Solve LeetCode #9 'Palindrome Number' [Easy].
- Loading branch information
1 parent
d55636a
commit 7867213
Showing
2 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
35 changes: 35 additions & 0 deletions
35
LeetCode/src/LeetCode.Challenges/Problems0XX/P009_PalindromeNumber/Solution.cs
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,35 @@ | ||
namespace LeetCode.Challenges.Problems0XX.P009_PalindromeNumber; | ||
|
||
public static class Solution | ||
{ | ||
public static bool IsPalindrome(int x) | ||
{ | ||
if (x < 0 || (x % 10 == 0 && x != 0)) | ||
{ | ||
return false; | ||
} | ||
|
||
List<int> digits = []; | ||
while (x >= 1) | ||
{ | ||
digits.Add(x % 10); | ||
x /= 10; | ||
} | ||
|
||
var left = 0; | ||
var right = digits.Count - 1; | ||
|
||
while (left <= right) | ||
{ | ||
if (digits[left] != digits[right]) | ||
{ | ||
return false; | ||
} | ||
|
||
left++; | ||
right--; | ||
} | ||
|
||
return true; | ||
} | ||
} |
27 changes: 27 additions & 0 deletions
27
...de/tests/LeetCode.Challenges.UnitTests/Problems0XX/P009_PalindromeNumber/SolutionTests.cs
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,27 @@ | ||
using FluentAssertions; | ||
using LeetCode.Challenges.Problems0XX.P009_PalindromeNumber; | ||
using Shouldly; | ||
using Xunit; | ||
|
||
namespace LeetCode.Challenges.UnitTests.Problems0XX.P009_PalindromeNumber; | ||
|
||
public class SolutionTests | ||
{ | ||
[Theory] | ||
[MemberData(nameof(TestData))] | ||
public void GivenNumber_WhenCallIsPalindrome_ThenResultAsExpected(int number, bool expectedResult) | ||
{ | ||
Solution.IsPalindrome(number).ShouldBe(expectedResult); | ||
} | ||
|
||
public static IEnumerable<object[]> TestData() | ||
{ | ||
yield return [1, true]; | ||
yield return [11, true]; | ||
yield return [121, true]; | ||
yield return [12321, true]; | ||
yield return [12, false]; | ||
yield return [123, false]; | ||
yield return [-121, false]; | ||
} | ||
} |