1
class Solution {
2
public:
3
string reformatNumber(string number) {
4
string temp; // stores the digits from string number
5
string ans; // stores final answer
6
int n = number.size();
7

8
for (auto ch : number)
9
if (isdigit(ch)) temp += ch;
10

11
int len = temp.size();
12
int i = 0;
13

14
while (len > 0) {
15
// check for different values of "len"
16
if (len > 4) { // if len > 4 -> make grp of 3 digits
17
ans += temp.substr(i, i + 3);
18
temp.erase(i, 3);
19
len = len - 3;
20
ans += "-";
21
}
22

23
else if (len == 3) { // if len == 3 -> make grp of 3 digits
24
ans += temp.substr(i, i + 3);
25
temp.erase(i, 3);
26
len = len - 3;
27
ans += "-";
28
}
29

30
else if (len == 2) { // if len == 2 -> make grp of 2 digits
31
ans += temp.substr(i, i + 2);
32
temp.erase(i, 2);
33
len = len - 2;
34
ans += "-";
35
}
36

37
else if (len == 4) { // if len == 4 -> make 1 grp of 2 digits & reduce the
38
// length by 2 units, in the next iteration it will
39
// automatically catch (len==2) condition
40
ans += temp.substr(i, i + 2);
41
temp.erase(i, 2);
42
ans += "-";
43
// ans += temp.substr(i,i+2); ------(1)
44
// temp.erase(i,2); ------(2)
45
// ans += "-"; ------(3)
46
len = len - 2; // *len = len-4* can be edited to *len = len-2*------(4)
47
}
48
}
49

50
ans.pop_back();
51
return ans;
52
}
53
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0