5 Functions [10 marks]
Suppose that you have a weight measured in grams that you want to convert to kilograms; for example, a weight of 10358 grams is equal to 10 kilograms and 358 grams. One way to find the number of kilograms is to remove the last three digits of the weight (in the example, we would remove the digits 358).
More generally, consider the problem of removing the last n
digits from an integer value v
where n
is an integer greater than or equal to zero. For example, suppose that v
is equal to 12345
, then removing the last n = 1
digits from v
yields the value
1234
with a removed digit of 5
.
Removing the last n = 2
digits from v
yields the value
123
with removed digits of 45
.
Removing the last n = 3
digits from v
yields the value
12
with removed digits of 345
.
Finally, suppose that n
is greater than or equal to 5
, then removing the last n
digits of v
yields the value
0
with removed digits of 12345
.
Create a function that removes the last n
digits of an integer value v
. Your function should satisfy the following constraints:
- it should be named
removeDigits
- it should return the two values
first
andremoved
wherefirst
is the number remaining after removing the digits andremoved
is the number containing the digits that were removed - it should have two input values
v
andn
wherev
is a positive integer value andn
is a positive integer equal to the number of digits to remove from the end ofv
.
5.1 Example usage
The examples given above can be computed as:
v = 12345;
% first = 1234, removed = 5
[first, removed] = removeDigits(v, 1);
% first = 123, removed = 45
[first, removed] = removeDigits(v, 2);
% first = 12, removed = 345
[first, removed] = removeDigits(v, 3);
% first = 0, removed = 12345
[first, removed] = removeDigits(v, 8);
If the removed digits start with one or more zeros then the leading zeros do not need to appear in removed
:
v = 1002;
% first = 1, removed = 2 (not 002)
[first, removed] = removeDigits(v, 3);