Given the array of digits (0 is also allowed), what is the minimal sum of two integers that are made of the digits contained in the array.
For example, array: 1 2 7 8 9. The min sum (129 + 78) should be 207
I assumed that numbers that begin with 0 (i.e 027) were invalid.
Ex: V=1 2 3 4 5 6 7 8 9
ans=16047
Ex: V=0 0 0 3 3 5 6 7
ans=6063
Here's the Matlab code I wrote:
function [S]=minsum(V)
% Returns the minimum sum of 2 integers using all of the digits in vector V
% ex. 12789 =179+28=207
if sum(V~=0)<2
display('function cannot compute minimun sum if there are not at least 2 integers')
return
end
v=sort(V)
L=numel(V);
n=sum(v==0);
if n~=0
vnew(1:2)=v(n+1:n+2);
vnew(3:(n+2))=0;
vnew(n+3:L)=v(n+3:end);
v=vnew
end
v1=v(1:2:end)
v2=v(2:2:end)
num1=0;
num2=0;
if mod(L,2)==0
for i=1:L/2
num1=num1+v1(i)*10^(L/2-i);
num2=num2+v2(i)*10^(L/2-i);
end
else
for i=1:(L+1)/2
num1=num1+v1(i)*10^((L+1)/2-i);
end
for j=1:(L-1)/2
num2=num2+v2(j)*10^((L-1)/2-j);
end
end
num1
num2
S=num1+num2
end
No comments:
Post a Comment