Download Add two strings representing numbers

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Add two strings representing numbers
Need:
n = '8877463' % A number as a string
length(n) % The number of digits in n
n(length(n)) % The LSD – in this case 3
th
n(length(n)­i+1) % The i LSD
n1 = n(x) – '0' % Convert a char to a number
s = n1 + n2 % Now we can add
mod(s,10) % LSD of the add
floor(s/10) % Carry digit
char(s+'0') % Convert to a char
Add two strings representing numbers
S1 =
8
4
2
1
5
7
3
6
8
9
+
S2 =
carry = 0
S3 =
Add two strings representing numbers
S1 =
8
4
2
1
7
3
6
8
5
+
S2 =
9
carry = 0
S3 =
First iteration (i=1):
n1 = S1(length(S1)­i+1)­'0';
Add two strings representing numbers
S1 =
8
4
2
1
+
S2 =
9
7
3
6
8
carry = 0
S3 =
5
First iteration (i=1):
n2 = S2(length(S2)­i+1)­'0';
Add two strings representing numbers
S1 =
8
4
2
1
+
S2 =
9
7
3
6
8
1 4
carry = 0
S3 =
5
First iteration (i=1):
n = n1 + n2 + carry;
Add two strings representing numbers
S1 =
8
4
2
1
+
S2 =
9
7
3
6
8
1 4
carry = 1
S3 =
5
First iteration (i=1):
carry = floor(n/10);
Add two strings representing numbers
S1 =
8
4
2
1
+
S2 =
9
7
3
6
8
1 4
tmp
carry = 1
S3 =
5
First iteration (i=1):
tmp = char(mod(n,10)+'0');
Add two strings representing numbers
S1 =
8
4
2
5
1
+
S2 =
9
7
3
6
8
4
S3 =
1 4
First iteration (i=1):
S3 = [tmp S3];
carry = 1
Add two strings representing numbers
S1 =
8
4
2
1
5
7
3
6
8
9
+
S2 =
4
S3 =
Second iteration (i=2):
carry = 1
Add two strings representing numbers
S1 =
8
4
2
7
3
6
5
1
+
S2 =
S3 =
8
9
4
Second iteration (i=2):
n1 = S1(length(S1)­i+1)­'0';
carry = 1
Add two strings representing numbers
S1 =
8
4
2
5
8
+
S2 =
S3 =
1
7
3
6
9
4
Second iteration (i=2):
n2 = S2(length(S2)­i+1)­'0';
carry = 1
Add two strings representing numbers
S1 =
8
4
2
5
8
+
S2 =
7
3
6
S3 =
1
Second iteration (i=2):
n = n1 + n2 + carry;
9
1 0
4
carry = 1
Add two strings representing numbers
S1 =
8
4
2
5
8
+
S2 =
7
3
6
S3 =
1
Second iteration (i=2):
carry = floor(n/10);
9
1 0
4
carry = 1
Add two strings representing numbers
S1 =
8
4
2
5
8
+
S2 =
S3 =
1
7
3
6
9
4
Second iteration (i=2):
tmp = char(mod(n,10)+'0');
1 0
tmp
carry = 1
Add two strings representing numbers
S1 =
8
4
2
5
8
+
S2 =
7
3
6
0
S3 =
1
Second iteration (i=2):
S3 = [tmp S3];
9
1 0
4
carry = 1
Add two strings representing numbers
S1 =
8
4
2
1
5
7
3
6
8
9
0
4
+
S2 =
S3 =
Third iteration (i=3):
carry = 1
Related documents