(MATLAB) Given a string s = \'011110010000000100010111\', the length of the long
ID: 3693811 • Letter: #
Question
(MATLAB) Given a string s = '011110010000000100010111', the length of the longest substring of s which contains consecutive ‘1's would be 4. Write a function named longest_ones, which accepts one input string consisting only of ‘0’ and ‘1’ characters. The function should return the size of the longest substring of consecutive ‘1’s. You are required to use the programming method (loops, conditional statements). The function should return the desired output regardless of the input string size. Here's an example of a function call: >> longest_ones('011110010000000100010111') ans = 4
Explanation / Answer
% Input x = '11010011111'
% Output p is 5
function p = longest_ones(x)
count = 0; p= 0;
for z = 1:length(x)
if x(z) == '1'
count = count + 1;
else
p= max(p, count);
count = 0;
end
end
p = max(p, count);
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.