Skip to content

Commit 2b2409c

Browse files
committed
PalindromeNumber: adjust solution & tests. Make it similar to ReverseString
1 parent 1a1acf7 commit 2b2409c

File tree

2 files changed

+16
-19
lines changed

2 files changed

+16
-19
lines changed

src/main/java/by/andd3dfx/numeric/PalindromeNumber.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,21 @@
77
*/
88
public class PalindromeNumber {
99

10-
public boolean isPalindrome(int x) {
10+
public static boolean isPalindrome(int x) {
1111
if (x < 0) {
1212
return false;
1313
}
1414

1515
var chars = String.valueOf(x).toCharArray();
16-
var len = chars.length;
17-
for (var i = 0; i < len / 2; i++) {
18-
if (chars[i] != chars[len - i - 1]) {
16+
var left = 0;
17+
var right = chars.length - 1;
18+
19+
while (left < right) {
20+
if (chars[left] != chars[right]) {
1921
return false;
2022
}
23+
left++;
24+
right--;
2125
}
2226
return true;
2327
}
Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,20 @@
11
package by.andd3dfx.numeric;
22

3-
import org.junit.Before;
43
import org.junit.Test;
54

5+
import static by.andd3dfx.numeric.PalindromeNumber.isPalindrome;
66
import static org.junit.Assert.assertFalse;
77
import static org.junit.Assert.assertTrue;
88

99
public class PalindromeNumberTest {
1010

11-
private PalindromeNumber palindromeNumber;
12-
13-
@Before
14-
public void setUp() throws Exception {
15-
palindromeNumber = new PalindromeNumber();
16-
}
17-
1811
@Test
19-
public void isPalindrome() {
20-
assertTrue(palindromeNumber.isPalindrome(121));
21-
assertTrue(palindromeNumber.isPalindrome(1568651));
22-
assertFalse(palindromeNumber.isPalindrome(-121));
23-
assertFalse(palindromeNumber.isPalindrome(123));
24-
assertFalse(palindromeNumber.isPalindrome(10));
25-
assertTrue(palindromeNumber.isPalindrome(0));
12+
public void testIsPalindrome() {
13+
assertTrue(isPalindrome(121));
14+
assertTrue(isPalindrome(1568651));
15+
assertFalse(isPalindrome(-121));
16+
assertFalse(isPalindrome(123));
17+
assertFalse(isPalindrome(10));
18+
assertTrue(isPalindrome(0));
2619
}
2720
}

0 commit comments

Comments
 (0)