JP Morgan Interview Question
Software EngineersCountry: India
If the input is a single string of numbers (ex '104875'), and the output should be '10*4*87-5', then here is my shot in JavaScript:
function insertStarsDashes(str) {
let i = 0
while(i < str.length) {
const current = str[i]
const next = str[i + 1]
// Check if current and next numbers are both even
if (current % 2 === 0 && next % 2 === 0) {
// Slice the string into two halves, insert the star
str = str.slice(0, i+1) + '*' + str.slice(i+1, str.length)
// If not, check if they are both odd and insert a dash
} else if (current % 2 === 1 && next % 2 === 1) {
str = str.slice(0, i+1) + '-' + str.slice(i+1, str.length)
}
i++
}
return str
}
In Java we can write something like below:
public class InsertStarBetweenEvenAndDashBetweenOdd {
public static void main(String[] args)
{
long l=104875l;
String s= ""+l;
StringBuilder s2= new StringBuilder("");
s2.append(s.charAt(0));
for(int i=1;i<s.length();i++)
{
int t1= Integer.parseInt(s.charAt(i-1)+"");
int t2= Integer.parseInt(s.charAt(i)+"");
s2.append((t1%2==0?(t2%2==0?"*"+s.charAt(i):s.charAt(i)):(t2%2!=0?"-"+s.charAt(i):s.charAt(i)))+"");
}
System.out.println(s2.toString());
}
}
public class InsertcCharBetweenOddAndEven {
public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader bfReader = new BufferedReader(reader);
String line = bfReader.readLine();
StringBuilder sb = new StringBuilder();
sb.append(line.charAt(0));
for(int i=1;i<line.length();i++){
if(line.charAt(i)%2==0 && line.charAt(i-1)%2==0) {
sb.append("*"+line.charAt(i));
}else if(line.charAt(i)%2!=0 && line.charAt(i-1)%2!=0) {
sb.append("-"+line.charAt(i));
}
else {
sb.append(line.charAt(i));
}
}
System.out.println(sb.toString());
}
}
def insert_bewteen(number):
strrrr = []
for i in range(0, len(number) - 1):
is_last = i == len(number) - 2
if int(number[i]) % 2 == 0 and int(number[i + 1]) % 2 == 0:
strrrr.append(number[i] + "*")
elif int(number[i]) % 2 == 1 and int(number[i + 1]) % 2 == 1:
strrrr.append(number[i] + "-")
else:
strrrr.append(number[i])
if is_last:
strrrr.append(number[i + 1]) #gdamn
print "".join(strrrr)
This question is not clear:
- steep September 16, 2017What is the input ?
Give an example and expected result