The challenge
Write a function stringy
that takes a size
and returns a string
of alternating '1s'
and '0s'
.
The string should start with a 1
.
A string with size
6 should return :'101010'
.
With size
4 should return : '1010'
.
With size
12 should return : '101010101010'
.
The size will always be positive and will only use whole numbers.
The solution in Java code
public class Solution {
public static String stringy(int size) {
int last = 1;
StringBuilder sb = new StringBuilder();
for (int i=0; i<size; i++) {
sb.append(last);
last = last==0 ? 1 : 0;
}
return sb.toString();
}
}
We could make this a little simpler by doing the following:
public class Solution {
public static String stringy(int size) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < size + 1; i++)
sb.append(i & 1);
return sb.toString();
}
}
An alternative solution using IntStream
:
import java.util.stream.IntStream;
import java.util.stream.Collectors;
public class Solution {
public static String stringy(int size) {
return IntStream.rangeClosed(1, size)
.map(i -> i % 2)
.mapToObj(String::valueOf)
.collect(Collectors.joining(""));
}
}
Test cases to validate our Java code
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.util.Random;
public class StringyExampleTests {
@Test
public void startTest() {
assertEquals("Your string should start with a 1", '1', Solution.stringy(3).charAt(0));
}
@Test
public void lengthTests() {
Random randGen = new Random();
for (int i = 0; i < 10; i++) {
int size = randGen.nextInt(50);
assertEquals("Wrong length using size " + size, size, Solution.stringy(size).length());
}
}
}