Given a string of digits, you should replace any digit below 5 with ‘0’ and any digit 5 and above with ‘1’. Return the resulting string.
function fakeBin(x){
for (var i = 0; i < x.length; i++) {
var outputString = "";
if (Number(x[i]) <= 4) {
outputString += "0";
} else if (Number(x[i]) >= 5) {
outputString += "1";
}
return outputString;
} //loop
} //function
If given [“4321”], the program will return only the first converted value. In this case, “0”.
How do I make the program continue replacing values with “1” and “0” because once either of the conditions of the if/else statement returns true, the loop finishes.
I may be wrong, but all I am asking if for help, not the answer. Thank You.
Move the return keyword outside of your loop statement. Return will halt and exist a function outputting a value. You placed it a tthe end of your loop, so your loop only runs once. Move it to the end of the entire function.
I fixed and it doesn’t work. I checked the solutions and someone had the same exact solution and it worked. Something may be wrong with the website. I am not sure
Also, I am not sure how JavaScript treats += for strings. In Java, the sign refers to StringBuilder, which works with mutable strings, that do not exist in JS. So it might be that you are working with basic strings, which will create a number of unnecessary intermediate strings.
Strings behave wonky when you begin using comparative operators because of the way they’re stored by JavaScript. If you want to know more about that I’m doing some practice with it right now I can share.
I should also point out that the else if is redundant here.
if (Number(x[i]) >= 4) {
outputString += "0";
} else if (Number(x[i]) >= 5) {
outputString += "1";
}
If you’ve already check that is is <=4, there is no need to check if whatever got passed is >= 5 - it is by definition. A simple else will do. This is sufficient - leaner and faster:
function fakeBin(x){
var arr = ;
x = “”+x+“”;
x.split(“”).join(“,”);
for(var i = 0;i<x.length;i++){
if(x[i] < 5){
arr.push(0);
}
else{
arr.push(1);
}
}
return arr.join(“”);
}
document.write(fakeBin(12345678));
//returns “00001111”
To continue the loop you can create an array and then push the resulting values into it with the loop just as I did on the above code
//Note that my code is JavaScript
Hello. This problem interests me a bit.
Isnt the issue here that you are using numbers as text to your function? Im thinking you will need some kind of parseint (x) in the for loop??