(Coderbyte) Dash Insert - Solução
Using the Java 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.
Solução:
import java.util.*;
import java.io.*;
import java.lang.*;
class Function {
String DashInsert(String str) {
char numero = str.charAt(0);
String nova = Character.toString(numero);
for (int i = 1; i < str.length(); i++) {
int num1 = Integer.parseInt(Character.toString(numero))%2;
int num2 = Integer.parseInt(Character.toString(str.charAt(i)))%2;
if ((num1 == 1) && ((num2 == 1))) {
nova += ("-" + str.charAt(i));
}
else {
nova += str.charAt(i);
}
numero = str.charAt(i);
}
return nova;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
Function c = new Function();
System.out.print(c.DashInsert(s.nextLine()));
}
}
Solução:
import java.util.*;
import java.io.*;
import java.lang.*;
class Function {
String DashInsert(String str) {
char numero = str.charAt(0);
String nova = Character.toString(numero);
for (int i = 1; i < str.length(); i++) {
int num1 = Integer.parseInt(Character.toString(numero))%2;
int num2 = Integer.parseInt(Character.toString(str.charAt(i)))%2;
if ((num1 == 1) && ((num2 == 1))) {
nova += ("-" + str.charAt(i));
}
else {
nova += str.charAt(i);
}
numero = str.charAt(i);
}
return nova;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
Function c = new Function();
System.out.print(c.DashInsert(s.nextLine()));
}
}
Comments
Post a Comment