-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseString
More file actions
50 lines (31 loc) · 775 Bytes
/
reverseString
File metadata and controls
50 lines (31 loc) · 775 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
Reverse String
Write a method that reverses a string.
For example, 'java interview' becomes 'weivretni avaj'.
*/
public String reverse(String s) {
String rv = "";
for (int i=0; i<s.length(); i++) {
rv += s.charAt(s.length()-1-i);
}
return rv;
}
// Reverse an integer number
public int reverse(int n) {
String s = String.valueOf(n); // int -> String
String rv = "";
for (int i=0; i<s.length(); i++) {
rv += s.charAt(s.length()-1-i);
}
return Integer.parseInt(rv); // String -> int
}
//more complicated way
public String reverse(String s) {
char[] c = s.toCharArray();
for (int i=0; i<c.length/2; i++) {
char tmp = c[i];
c[i] = c[s.length()-1-i];
c[s.length()-1-i] = tmp;
}
return String.valueOf(c); // char array -> String
}