How do you create the number as mentioned below?

1 次查看(过去 30 天)
If we write all positive integers in a row (in our decimal system) we get 123456789101112131415161718192021222324252627282930
Write a function that returns the n-th digit of this gigantic number.
  2 个评论
Juull01
Juull01 2016-10-8
I know how to solve the last part, but I really have no idea how to create that hugh number in Matlab.
Thanks in advance

请先登录,再进行评论。

采纳的回答

Massimo Zanetti
Massimo Zanetti 2016-10-8
Here it is
m=1:30;
n=12;
s=regexprep(num2str(m),' ','')
s(n)
  2 个评论
Juull01
Juull01 2016-10-8
Thank so much for your help! I really appreciate it I worked on it for like 2 hours and couldn't get the answer.

请先登录,再进行评论。

更多回答(3 个)

Marc Jakobi
Marc Jakobi 2016-10-8
I won't tell you how to do it since this sounds like homework, but here are some functions that may help you.
str2double() % convert string to double
num2str() % convert double to string
to combine two strings:
a = 'a';
b = 'b';
ab = [a, b];
returns
'ab'
and
ab(2)
returns
ab(2) = 'b'

Star Strider
Star Strider 2016-10-8
Without using strings at all, this works strictly numerically:
M1 = repmat([0:9], 10, 1);
M2 = repmat([0:9]', 1, 10);
M3 = cat(3,M1, M2);
M4 = reshape(M3, [], 2);
M5 = reshape(M4', 1, []);
Out = [1:9 M5(21:end)]

Walter Roberson
Walter Roberson 2016-10-9
编辑:Walter Roberson 2016-10-9
For amusement, a Maple version of the general solution, using direct numeric calculations without creating the intermediate values.
H := proc (M)
local min_numdig, contrib_from_min, leftover, dp1, base_number, dig, dig_offset;
min_numdig := floor(((1/9)*ln(10)+LambertW((1/90)*ln(10)*(9*M-1)*10^(8/9)))/ln(10));
dp1 := min_numdig+1;
contrib_from_min := (1/90)*10^dp1*(9*min_numdig-1)+1/9;
leftover := M-contrib_from_min;
if leftover = 0
then
dig := "9"
else
base_number := 10^min_numdig-1+floor(leftover/dp1);
dig_offset := `mod`(leftover, dp1);
if dig_offset = 0
then
dig_offset := dp1
else
base_number := base_number+1
end if;
dig := sprintf("%d", base_number)[dig_offset]
end if;
dig
end proc;
Note: this fails on 0 due to both a Maple technicality and a logic bug. The mathematics of it is presented without proof.
No MATLAB version of this will be provided, as the question is obviously a homework question.

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by