Dash Insert Coderbyte Solutions

0

Have the function DashInsert(str) insert dashes ('-') between each two odd numbers in str. 

For example: if str is 454793 the output should be 4547-9-3. Don't count zero as an odd number.

Dash Insert  Coderbyte In Java


import java.util.Scanner;

public class DashInsert {
String DashInsert(String str) {
char[] nums = str.toCharArray();
int prevNum = Integer.parseInt(String.valueOf(nums[0]));
StringBuilder result = new StringBuilder(String.valueOf(prevNum));
for (int i = 1; i < nums.length; i++) {
int num = Integer.parseInt(String.valueOf(nums[i]));

if (num != 0 && prevNum % 2 == 1 && num % 2 == 1) {
result.append("-");
}
result.append(num);
prevNum = num;
}

return result.toString();
}

public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
DashInsert c = new DashInsert();
System.out.print(c.DashInsert(s.nextLine()));
}
}

Dash Insert  Coderbyte In Python


def DashInsert(num):
result = ""
for i in str(num):
if (len(result)==0):
result += i
continue
if int(i)%2 == 1 and int(result[-1])%2==1:
result += "-" + i
else:
result += i
return result

# keep this function call here
# to see how to enter arguments in Python scroll down
print DashInsert(raw_input())

Dash Insert  Coderbyte In JavaScript

Using the JavaScript language, have the function DashInsert(str) insert dashes ('-') between each two odd numbers in str. 

For example: if str is 454793 the output should be 4547-9-3. Don't count zero as an odd number.


function DashInsert(str) {

var idx = 0;
while (idx < str.length-1) {
if (Number(str[idx]) % 2 === 1 && Number(str[idx+1]) % 2 === 1) {
str = str.slice(0,idx+1) + "-" + str.slice(idx+1);
idx = idx + 2;
}
else {
idx++;
}
}
return str;
}

Explanation:

I am going to loop through each number in the string. Test if number is odd using modulus. If odd then check if next number is also odd. I have two odd numbers then insert dash into the string.

Disclaimer: The above Problem is generated by Coderbyte but the Solution is provided by ShouterFolk.


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !