第一题 Problem 15. Find the longest sequence of 1's in a binary sequence.
Given a string such as
s = '011110010000000100010111'
find the length of the longest string of consecutive 1's. In this example, the answer would be 4.
Example:
Input x = '110100111'
Output y is 3
在只有‘0’和‘1’的字符串x中求‘1’连续出现的最大长度,由于只存在‘1’和‘0’,可以利用‘0’对x进行分割,得到每个1连续出现的子字符串,并存放在元组内,然后依次遍历子字符串获取长度即可(元组索引需要使用{})
function y = lengthOnes(x)
x=strsplit(x,'0');
y=0;
for i=1:length(x)
y=max(y,length(x{i}));
end
end
第二题 Problem 2522. Convert given decimal number to binary number.
Convert given decimal number to binary number.
Example x=10, then answer must be 1010.
将输入的十进制数转为二进制数。
不想麻烦的可以直接使用dec2bin将输入的十进制转为二进制,但输出为字符串,再使用str2num即可。
function y = dec_bin(x)
y = str2num(dec2bin(x));
end
第三题 Problem 2678. Find out sum and carry of Binary adder
Find out sum and carry of a binary adder if previous carry is given with two bits (x and y) for addition.
Examples
Previous carry is 1 and x=y=1. Addition is 1 and carry is also 1.
Previous carry is 0 and x=y=1. Addition is 0 and carry is also 1.
Previous carry is 0 and x=1, y=0. Addition is


最低0.47元/天 解锁文章
1165

被折叠的 条评论
为什么被折叠?



