Problem 568. Number of 1s in a binary string
6 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
採用された回答
Les Beckham
2023 年 9 月 8 日
The find() function returns the index of all non-zero elements in the input. ASCII characters (like '0' and '1') are all non-zero (numerically) so your function will just return the length of the input string.
Example:
find('1011010')
length(find('1011010'))
There are a lot of ways to solve this problem. Look at this documentation page for one way: find characters
3 件のコメント
Les Beckham
2023 年 9 月 8 日
Mathworks has several other tutorials in addition to the Onramp.
Check this page that lists some more: Self-Paced Online Courses
その他の回答 (1 件)
Harald
2023 年 9 月 8 日
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 件のコメント
Dyuman Joshi
2023 年 9 月 8 日
"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.
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!