Problem 568. Number of 1s in a binary string
Afficher commentaires plus anciens
Thats the question:
Find the number of 1s in the given binary string. Example. If the input string is '1100101', the output is 4. If the input string is '0000', the output is 0
I wrote this code, but I don't understand, what is wrong with it.
function y = one(x)
y = length(find(x))
end
Réponse acceptée
Plus de réponses (1)
Harald
le 8 Sep 2023
3 votes
Hi,
find is intended for numerical non-0 elements rather than non-'0'. Instead, I would use == to compare to '0', and I would also use sum or nnz rather than length.
Best wishes,
Harald
6 commentaires
Dyuman Joshi
le 8 Sep 2023
+1 for using just logical indexing with sum/nnz over length
Image Analyst
le 8 Sep 2023
Mayla
le 8 Sep 2023
Harald
le 8 Sep 2023
Hi,
you need to compare to '1' instead of 1.
Also, avoid using ans. Assign to a variable instead:
isOne = x=='1';
y=sum(isOne)
% or, in one line:
y=sum(x == '1')
Best wishes,
Harald
"and it didn't work."
Because you are comparing with a numerical value
x='1011010';
x==1
What you want to do is compare with a character
x=='1'
"And why can't I only use sum(x)?"
Because that will give the sum of the values of x, which is not what the questions asks for.
What you want is, the total number of values i.e. sum where x isequal to '1'. So that's what is done.
Dyuman Joshi
le 8 Sep 2023
@Image Analyst please check again
Catégories
En savoir plus sur Entering Commands dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!