forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1694.java
35 lines (34 loc) · 1.17 KB
/
_1694.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
31
32
33
34
35
package com.fishercoder.solutions;
public class _1694 {
public static class Solution1 {
public String reformatNumber(String number) {
StringBuilder sb = new StringBuilder();
for (char c : number.toCharArray()) {
if (Character.isDigit(c)) {
sb.append(c);
}
}
String cleaned = sb.toString();
sb.setLength(0);
for (int i = 0; i < cleaned.length(); ) {
if (i + 4 == cleaned.length()) {
sb.append(cleaned.substring(i, i + 2));
sb.append("-");
sb.append(cleaned.substring(i + 2));
break;
} else if (i + 3 <= cleaned.length()) {
sb.append(cleaned.substring(i, i + 3));
sb.append("-");
i += 3;
} else {
sb.append(cleaned.substring(i));
break;
}
}
if (sb.charAt(sb.length() - 1) == '-') {
sb.setLength(sb.length() - 1);
}
return sb.toString();
}
}
}