回答編集履歴
2
追記
answer
CHANGED
@@ -1,2 +1,74 @@
|
|
1
1
|
`nums[0]`と`nums[num.length-1]`をスワップすればいいと思いますよ。
|
2
|
-
負号が付いていれば`nums[1]`ですね。
|
2
|
+
負号が付いていれば`nums[1]`ですね。
|
3
|
+
|
4
|
+
書いてみた
|
5
|
+
---
|
6
|
+
元のコードと全く違いますが。
|
7
|
+
```Java
|
8
|
+
import java.util.NoSuchElementException;
|
9
|
+
import java.util.Scanner;
|
10
|
+
|
11
|
+
class ReverseInt {
|
12
|
+
static String lstrip(String src, String removeChars) {
|
13
|
+
return src.replaceFirst(
|
14
|
+
String.format("^[%s]+", removeChars), ""
|
15
|
+
);
|
16
|
+
}
|
17
|
+
static StringBuilder lstrip(StringBuilder src, String removeChars) {
|
18
|
+
return new StringBuilder(
|
19
|
+
lstrip(src.toString(), removeChars)
|
20
|
+
);
|
21
|
+
}
|
22
|
+
|
23
|
+
static String reverse(String input) throws NumberFormatException {
|
24
|
+
Integer.parseInt(input);
|
25
|
+
StringBuilder builder = new StringBuilder(input);
|
26
|
+
|
27
|
+
boolean isNegative = builder.toString().startsWith("-");
|
28
|
+
if(isNegative) {
|
29
|
+
builder = builder.deleteCharAt(0);
|
30
|
+
}
|
31
|
+
|
32
|
+
builder.reverse();
|
33
|
+
builder = lstrip(builder, "0");
|
34
|
+
|
35
|
+
if(isNegative) {
|
36
|
+
builder.insert(0, "-");
|
37
|
+
}
|
38
|
+
|
39
|
+
return builder.toString();
|
40
|
+
}
|
41
|
+
|
42
|
+
public static void main(String[] args) {
|
43
|
+
try(Scanner sc = new Scanner(System.in)) {
|
44
|
+
while(sc.hasNext()) {
|
45
|
+
String input = sc.nextLine();
|
46
|
+
try {
|
47
|
+
System.out.println(reverse(input));
|
48
|
+
}
|
49
|
+
catch(NumberFormatException e) {
|
50
|
+
System.out.println("\"" + input + "\" cannot be interpreted as an integer.");
|
51
|
+
}
|
52
|
+
}
|
53
|
+
}
|
54
|
+
}
|
55
|
+
}
|
56
|
+
```
|
57
|
+
|
58
|
+
**入力例**
|
59
|
+
```plain
|
60
|
+
12345
|
61
|
+
-123
|
62
|
+
hoge
|
63
|
+
1000
|
64
|
+
-100
|
65
|
+
```
|
66
|
+
|
67
|
+
**出力例** [Wandbox](https://wandbox.org/permlink/bgWclCumxPyILXE1)
|
68
|
+
```plain
|
69
|
+
54321
|
70
|
+
-321
|
71
|
+
"hoge" cannot be interpreted as an integer.
|
72
|
+
1
|
73
|
+
-1
|
74
|
+
```
|
1
負数の判定忘れてた
answer
CHANGED
@@ -1,1 +1,2 @@
|
|
1
|
-
`nums[0]`と`nums[num.length-1]`をスワップすればいいと思いますよ。
|
1
|
+
`nums[0]`と`nums[num.length-1]`をスワップすればいいと思いますよ。
|
2
|
+
負号が付いていれば`nums[1]`ですね。
|