How to “Dashatize It” in Java

The challenge

Given a variable n,

If n is an integer, Return a string with dash'-'marks before and after each odd integer, but do not begin or end the string with a dash mark. If n is negative, then the negative sign should be removed.

If n is not an integer, return an empty value.

Ex:

dashatize(274) -> '2-7-4' dashatize(6815) -> '68-1-5'
Code language: JavaScript (javascript)

The solution in Java code

Option 1:

public class Solution { public static String dashatize(int num) { String n = String.valueOf(Math.abs(num)).replaceAll("-", ""); return java.util.Arrays.asList(n.split("")).stream() .map(ch -> Integer.valueOf(ch) % 2 !=0 ? "-"+ch+"-" : ch) .collect(java.util.stream.Collectors.joining("")) .replaceAll("--", "-") .replaceAll("^-+", "") .replaceAll("-+$", ""); } }
Code language: Java (java)

Option 2:

public class Solution { public static String dashatize(final int number) { return String.valueOf(number) .replaceAll("([13579])", "-$1-") .replaceAll("--", "-") .replaceAll("^-|-$", ""); } }
Code language: Java (java)

Option 3:

import java.util.*; public class Solution { public static String dashatize(int num) { String str = String.valueOf(num); if(str.charAt(0) == '-') str = str.substring(1); return String.join("-",str.split("(?=[1,3,5,7,9])|(?<=[1,3,5,7,9])")); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testBasic() { assertEquals("2-7-4", Solution.dashatize(274)); assertEquals("5-3-1-1", Solution.dashatize(5311)); assertEquals("86-3-20", Solution.dashatize(86320)); assertEquals("9-7-4-3-02", Solution.dashatize(974302)); } @Test public void testWeird() { assertEquals("0", Solution.dashatize(0)); assertEquals("1", Solution.dashatize(-1)); assertEquals("28-3-6-9", Solution.dashatize(-28369)); } @Test public void testEdgeCases() { assertEquals("2-1-4-7-48-3-64-7", Solution.dashatize(Integer.MAX_VALUE)); assertEquals("2-1-4-7-48-3-648", Solution.dashatize(Integer.MIN_VALUE)); assertEquals("1-1-1-1-1-1-1-1-1-1", Solution.dashatize(-1111111111)); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments