Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Oscar Kam
4,281 PointsQuestion about interleaving numbers.
I am a bit new to English and Java, and am having trouble with a logic problem on Coding Bat. I found a java logic problem where we are given two ints. We must return the two ints interwoven. so if we are given 1234 and 5678, it should print 15263748. And if one of the ints is less than 4 digits, the remaining digits should be replaced with 0.
I usually don't ask for help with these but I'm quite bamboozled by this one. I was thinking I'd make the ints into arrays and store the digits, then return them in an alternating fashion. But, I don't know how to replace the digits with 0 if it is under 4 digits.
Thank you!
1 Answer
Kourosh Raeen
23,733 PointsHi Oliver - You could convert the integers to strings and then based on their length pad them with zeros. Give it a try and if you're still stuck take a look at my solution below. Also, there's probably a more elegant solution that mine:
import java.util.Scanner;
public class Interleave {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter the first number: ");
int num1 = reader.nextInt();
System.out.println("\nEnter the second number: ");
int num2 = reader.nextInt();
System.out.println("\n" + num1);
System.out.println("\n" +num2);
System.out.println("\n" + interleave(num1, num2));
}
public static int interleave(int num1, int num2) {
String strNum1 = Integer.toString(num1);
String strNum2 = Integer.toString(num2);
if (strNum1.length() == 3) {
strNum1 += "0";
}
if (strNum1.length() == 2) {
strNum1 += "00";
}
if (strNum1.length() == 1) {
strNum1 += "000";
}
if (strNum2.length() == 3) {
strNum2 += "0";
}
if (strNum2.length() == 2) {
strNum2 += "00";
}
if (strNum2.length() == 1) {
strNum2 += "000";
}
String strInterleave = "";
for (int i=0; i < 4; i++) {
strInterleave += strNum1.charAt(i);
strInterleave += strNum2.charAt(i);
}
return Integer.parseInt(strInterleave);
}
}