回答編集履歴

2

追記

2018/03/09 05:58

投稿

LouiS0616
LouiS0616

スコア35658

test CHANGED
@@ -1,3 +1,147 @@
1
1
  `nums[0]`と`nums[num.length-1]`をスワップすればいいと思いますよ。
2
2
 
3
3
  負号が付いていれば`nums[1]`ですね。
4
+
5
+
6
+
7
+ 書いてみた
8
+
9
+ ---
10
+
11
+ 元のコードと全く違いますが。
12
+
13
+ ```Java
14
+
15
+ import java.util.NoSuchElementException;
16
+
17
+ import java.util.Scanner;
18
+
19
+
20
+
21
+ class ReverseInt {
22
+
23
+ static String lstrip(String src, String removeChars) {
24
+
25
+ return src.replaceFirst(
26
+
27
+ String.format("^[%s]+", removeChars), ""
28
+
29
+ );
30
+
31
+ }
32
+
33
+ static StringBuilder lstrip(StringBuilder src, String removeChars) {
34
+
35
+ return new StringBuilder(
36
+
37
+ lstrip(src.toString(), removeChars)
38
+
39
+ );
40
+
41
+ }
42
+
43
+
44
+
45
+ static String reverse(String input) throws NumberFormatException {
46
+
47
+ Integer.parseInt(input);
48
+
49
+ StringBuilder builder = new StringBuilder(input);
50
+
51
+
52
+
53
+ boolean isNegative = builder.toString().startsWith("-");
54
+
55
+ if(isNegative) {
56
+
57
+ builder = builder.deleteCharAt(0);
58
+
59
+ }
60
+
61
+
62
+
63
+ builder.reverse();
64
+
65
+ builder = lstrip(builder, "0");
66
+
67
+
68
+
69
+ if(isNegative) {
70
+
71
+ builder.insert(0, "-");
72
+
73
+ }
74
+
75
+
76
+
77
+ return builder.toString();
78
+
79
+ }
80
+
81
+
82
+
83
+ public static void main(String[] args) {
84
+
85
+ try(Scanner sc = new Scanner(System.in)) {
86
+
87
+ while(sc.hasNext()) {
88
+
89
+ String input = sc.nextLine();
90
+
91
+ try {
92
+
93
+ System.out.println(reverse(input));
94
+
95
+ }
96
+
97
+ catch(NumberFormatException e) {
98
+
99
+ System.out.println("\"" + input + "\" cannot be interpreted as an integer.");
100
+
101
+ }
102
+
103
+ }
104
+
105
+ }
106
+
107
+ }
108
+
109
+ }
110
+
111
+ ```
112
+
113
+
114
+
115
+ **入力例**
116
+
117
+ ```plain
118
+
119
+ 12345
120
+
121
+ -123
122
+
123
+ hoge
124
+
125
+ 1000
126
+
127
+ -100
128
+
129
+ ```
130
+
131
+
132
+
133
+ **出力例** [Wandbox](https://wandbox.org/permlink/bgWclCumxPyILXE1)
134
+
135
+ ```plain
136
+
137
+ 54321
138
+
139
+ -321
140
+
141
+ "hoge" cannot be interpreted as an integer.
142
+
143
+ 1
144
+
145
+ -1
146
+
147
+ ```

1

負数の判定忘れてた

2018/03/09 05:58

投稿

LouiS0616
LouiS0616

スコア35658

test CHANGED
@@ -1 +1,3 @@
1
1
  `nums[0]`と`nums[num.length-1]`をスワップすればいいと思いますよ。
2
+
3
+ 負号が付いていれば`nums[1]`ですね。