File tree Expand file tree Collapse file tree 1 file changed +22
-6
lines changed Expand file tree Collapse file tree 1 file changed +22
-6
lines changed Original file line number Diff line number Diff line change 1
1
function multiply ( num1 , num2 ) {
2
2
// your code here
3
- let aux = 0 ;
4
- if ( num1 < 0 ) {
5
- for ( let times = 0 ; times < num2 ; times ++ ) aux += num1 ;
6
- } else {
7
- for ( let times = 0 ; times < num1 ; times ++ ) aux += num2 ;
3
+ let result = 0 ;
4
+ let isNegative = false ;
5
+
6
+ // Check if the result will be negative
7
+ if ( ( num1 < 0 && num2 > 0 ) || ( num1 > 0 && num2 < 0 ) ) {
8
+ isNegative = true ;
9
+ }
10
+
11
+ // Convert both numbers to positive
12
+ num1 = Math . abs ( num1 ) ;
13
+ num2 = Math . abs ( num2 ) ;
14
+
15
+ // Add num1 to result num2 times
16
+ for ( let i = 0 ; i < num2 ; i ++ ) {
17
+ result += num1 ;
8
18
}
9
- return aux ;
19
+
20
+ // If the result should be negative, negate it
21
+ if ( isNegative ) {
22
+ result = - result ;
23
+ }
24
+
25
+ return result ;
10
26
}
11
27
12
28
let output = multiply ( 2 , - 7 ) ;
You can’t perform that action at this time.
0 commit comments