-
Notifications
You must be signed in to change notification settings - Fork 16
/
ReformatPhoneNumber.java
30 lines (28 loc) · 1.07 KB
/
ReformatPhoneNumber.java
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
import java.util.LinkedList;
import java.util.Queue;
public class ReformatPhoneNumber {
public String reformatNumber(String number) {
final Queue<Character> digits = getDigits(number);
final StringBuilder result = new StringBuilder();
int count = 3;
while (!digits.isEmpty()) {
if (digits.size() == 4 && count % 3 == 0) {
result.append(count == 3 ? "" : '-').append(digits.poll()).append(digits.poll())
.append('-').append(digits.poll()).append(digits.poll());
break;
}
result.append(count == 0 ? '-' : "").append(digits.poll());
count = (count + 1) % 3;
}
return result.toString();
}
private Queue<Character> getDigits(String number) {
final Queue<Character> digits = new LinkedList<>();
for (int index = 0 ; index < number.length() ; index++) {
if (Character.isDigit(number.charAt(index))) {
digits.add(number.charAt(index));
}
}
return digits;
}
}