Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit81949ac

Browse files
author
applewjg
committed
Palindrome Number
Change-Id: Idcdf65b43af057221a95406932232b354dbe9ed4
1 parente7101d1 commit81949ac

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎PalindromeNumber.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Aug 22, 2013
4+
Problem: Palindrome Number
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/palindrome-number/
7+
Notes:
8+
Determine whether an integer is a palindrome. Do this without extra space.
9+
Some hints:
10+
Could negative integers be palindromes? (ie, -1) (No!)
11+
If you are thinking of converting the integer to string, note the restriction of using extra space.
12+
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer",
13+
you know that the reversed integer might overflow. How would you handle such case?
14+
There is a more generic way of solving this problem.
15+
16+
Solution: 1. Count the number of digits first (traverse once) then check the digits from both sides to center.
17+
2. Reverse the number, then check to see if x == reverse(x).
18+
3. Recursion (interesting but a little hard to understand). -> See C++.
19+
*/
20+
publicclassSolution {
21+
publicbooleanisPalindrome(intx) {
22+
returnisPalindrome_2(x);
23+
}
24+
publicbooleanisPalindrome_1(intx) {
25+
if (x <0)returnfalse;
26+
intd =1;
27+
while (x /d >=10)d *=10;
28+
while (d >1) {
29+
if (x %10 !=x /d)returnfalse;
30+
x = (x %d) /10;
31+
d /=100;
32+
}
33+
returntrue;
34+
}
35+
publicbooleanisPalindrome_2(intx) {
36+
if (x <0)returnfalse;
37+
returnx ==reverse(x);
38+
}
39+
publicintreverse(intx) {
40+
intres =0;
41+
while (x >0) {
42+
res =res *10 +x %10;
43+
x =x /10;
44+
}
45+
returnres;
46+
}
47+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp