java version "1.8.0_92"
Hi,
I am trying to convert this function that uses iteration to a recursive one.
public static String bitConversion(int x) {
List<Integer> binaryList = new ArrayList<Integer>();
while(x > 0) {
binaryList.add(x % 2);
x /= 2;
}
StringBuilder stringBuilder = new StringBuilder();
for(Integer binary : binaryList) {
stringBuilder.append(binary.toString());
}
return stringBuilder.toString();
}
My attempt is this
public static String bitConversion(int x) {
List<Integer> binaryList = new ArrayList<Integer>();
if(x <= 0) {
StringBuilder stringBuilder = new StringBuilder();
for(Integer binary : binaryList) {
stringBuilder.append(binary.toString());
}
return stringBuilder.toString();
}
else {
binaryList.add(x % 2);
return bitConvert(x / 2);
}
}
One thing is that I need to have the binaryList to add the Integer to. In the first condition when everything is finished I need to put them into a stringbuilder. And in the second condition I need to add them to the list. So the List need to be global to both condition. But as the function calls itself the List will be re-initialized each time.
Can any advice on the best way to write this recursive function?
Many thanks for any suggestions.