|
1 | 1 | // Predict and explain first... |
2 | 2 |
|
3 | 3 | /* |
4 | | -we can not run this function because we settle the variable with const and this won't allow us to reassign |
5 | | -the new value which we are trying to test in the console.log() |
| 4 | + - If we run this code. nothing will happen because the function is not called. |
6 | 5 |
|
7 | | -const num = 103; |
| 6 | + -once we invoke the function this will take the number and converted into string to manipulate and take the las digit and return the new string 42 => will return 2. |
8 | 7 |
|
9 | | -function getLastDigit() { |
10 | | - return num.toString().slice(-1); |
| 8 | + const num = 103; |
| 9 | +
|
| 10 | + function getLastDigit() { |
| 11 | + return num.toString().slice(-1); |
11 | 12 | } |
12 | 13 |
|
13 | 14 | */ |
14 | 15 |
|
15 | 16 | //=========== This will work ============== |
| 17 | +// This program should tell the user the last digit of each number. |
| 18 | +// Explain why getLastDigit is not working properly - correct the problem |
| 19 | + |
| 20 | + |
| 21 | +const num = 103; |
16 | 22 |
|
17 | 23 | function getLastDigit(num) { |
18 | | - return num.toString().slice(-1); |
| 24 | + return num.toString().slice(-1); |
19 | 25 | } |
20 | 26 |
|
21 | | - |
| 27 | +console.log(`The last digit of 42 is ${getLastDigit(num)}`); |
22 | 28 | console.log(`The last digit of 42 is ${getLastDigit(42)}`); |
23 | 29 | console.log(`The last digit of 105 is ${getLastDigit(105)}`); |
24 | 30 | console.log(`The last digit of 806 is ${getLastDigit(806)}`); |
25 | 31 |
|
26 | | -// This program should tell the user the last digit of each number. |
27 | | -// Explain why getLastDigit is not working properly - correct the problem |
| 32 | + |
| 33 | + |
| 34 | +//=========== finding the middle digit ============== |
| 35 | +// Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 |
| 36 | +// Value: 2 0 5 5 5 6 4 2 3 2 5 6 9 |
| 37 | + |
| 38 | +function getMiddleDigit(num) { |
| 39 | + const str = num.toString(); |
| 40 | + // console.log(str); |
| 41 | + |
| 42 | + const middleIndex = Math.floor(str.length / 2); // 13/2 = 6.5 math.floor round the number to the nearest integer 6. |
| 43 | + // console.log(middleIndex); |
| 44 | + |
| 45 | + return str[middleIndex]; //we can access to the position 6 which contains the value '4' |
| 46 | +} |
| 47 | + |
| 48 | +console.log(`The middle of 105 is ${getMiddleDigit(2055564232569)}`); |
0 commit comments