MATLAB function adds two nonnegative integers where x has at least as many digits as y

1 回表示 (過去 30 日間)
Sophie Culhane
Sophie Culhane 2020 年 10 月 12 日
回答済み: Ameer Hamza 2020 年 10 月 12 日
My task is to write a MATLAB function that adds two nonnegative integers, assuming that x has at least as many digits as y. x,y, and x_plus_y are row vectors representing nonnegative integers. Each element of the vectors stores one digit of a nonnegative integer. (12345 is represented by [1 2 3 4 5]). I need assistance in storing these numbers as vectors as I am lost on how to do so.
Here is what I have so far, and I apologize that it is not much.
function x_plus_y = hw24(x,y)
%
x = zeros(size(x));
y = zeros(size(y));
x_plus_y = zeros(size(x,y));
for k = 1:length(x)
for k = 1:length(y)
x_plus_y = x(k) + y(k);
end
end

回答 (2 件)

Matt J
Matt J 2020 年 10 月 12 日
Hint: You can convert from vector form to a single number as follows
x=[1 2 3 4 5];
xx=x*10.^(4:-1:0).'
xx = 12345

Ameer Hamza
Ameer Hamza 2020 年 10 月 12 日
Check this alternate method
function x_plus_y = hw24(x,y)
nx = numel(x);
ny = numel(y);
n = max(nx, ny);
x_plus_y = zeros(1, n+1);
x_plus_y = x_plus_y + [zeros(1,n-nx+1) x];
x_plus_y = x_plus_y + [zeros(1,n-ny+1) y];
x_plus_y = mod(x_plus_y,10) + [floor(x_plus_y(2:end)/10) 0];
end
Result
>> x = [9 9 9 9 9];
>> y = [8 6 3 1 9];
>> z = hw24(x, y)
z =
1 8 6 3 1 8

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by