Skip to content

Commit 7b61274

Browse files
committed
Dash Insert
1 parent f420dc9 commit 7b61274

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/easy/DashInsert.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package easy;
2+
3+
/**
4+
* Have the function DashInsert(str) insert dashes ('-')
5+
* between each two odd numbers in str. For example:
6+
* if str is 454793 the output should be 4547-9-3.
7+
* Don't count zero as an odd number.
8+
*/
9+
public class DashInsert {
10+
11+
/**
12+
* Dash Insert function.
13+
*
14+
* @param str input string
15+
* @return a string with dashes between each two odd numbers
16+
*/
17+
private static String dashInsert(String str) {
18+
StringBuilder dashed = new StringBuilder();
19+
char[] chars = str.toCharArray();
20+
for (int i = 1; i < chars.length + 1; i++) {
21+
int c1 = Character.getNumericValue(chars[i - 1]);
22+
int c2 = i < chars.length ? Character.getNumericValue(chars[i]) : 0;
23+
dashed.append(c1);
24+
if (c1 % 2 != 0 && c2 % 2 != 0) {
25+
dashed.append("-");
26+
}
27+
}
28+
return dashed.toString();
29+
}
30+
31+
/**
32+
* Entry point.
33+
*
34+
* @param args command line arguments
35+
*/
36+
public static void main(String[] args) {
37+
var result1 = dashInsert("454793");
38+
System.out.println(result1);
39+
var result2 = dashInsert("25928");
40+
System.out.println(result2);
41+
}
42+
43+
}

0 commit comments

Comments
 (0)