You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Question 1: sum of all natural numbers from 1 to n
3
+
4
+
sum of 1 to 5: 15
5
+
*/
6
+
7
+
functionsumOfNaturalNumber(num){
8
+
letsum=0;
9
+
for(leti=1;i<=num;i++){
10
+
sum=sum+i;
11
+
}
12
+
returnsum;
13
+
}
14
+
15
+
console.log(sumOfNaturalNumber(5))//15
16
+
console.log(sumOfNaturalNumber(10))//55
17
+
console.log(sumOfNaturalNumber(8))//36
18
+
19
+
20
+
/*
21
+
Question 2: Sum of digits of a number
22
+
23
+
1287: 1+2+8+7 = 18
24
+
25
+
*/
26
+
27
+
functionsumOfDigits(num){
28
+
letsum=0;
29
+
while(num>0){
30
+
sum+=num%10;
31
+
num=Math.floor(num/10);
32
+
}
33
+
returnsum;
34
+
}
35
+
36
+
console.log(sumOfDigits(1287))//18
37
+
38
+
/*
39
+
Question 3: count the number of digits of a number
40
+
34252: 5
41
+
-121 = 3
42
+
*/
43
+
44
+
functioncountDigits(num){
45
+
num=Math.abs(num);
46
+
letcount=0;
47
+
do{
48
+
count++;
49
+
num=Math.floor(num/10);
50
+
}while(num>0);
51
+
returncount;
52
+
}
53
+
54
+
console.log(countDigits(121))//3
55
+
console.log(countDigits(-1211413131))//10
56
+
57
+
/*
58
+
Question 4: Given an integer x, return true if x is a palindrome, and false otherwise.
59
+
60
+
A palindrome number is a number that remains the same when digits are reversed
61
+
*/
62
+
63
+
letisPalindrome=function(x){
64
+
letcopyNum=x,reverseNum=0;
65
+
66
+
while(copyNum>0){
67
+
constlastDigit=copyNum%10;
68
+
reverseNum=reverseNum*10+lastDigit;
69
+
copyNum=Math.floor(copyNum/10)
70
+
}
71
+
72
+
returnx===reverseNum
73
+
};
74
+
75
+
console.log(isPalindrome(121))//true
76
+
console.log(isPalindrome(1234))//false
77
+
78
+
/*
79
+
Question 5: Find nth fibonacci number
80
+
81
+
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1
82
+
83
+
Fibonacci Sequence: 0 1 1 2 3 5 8...
84
+
*/
85
+
86
+
letfib=function(n){
87
+
if(n<2){
88
+
returnn;
89
+
}
90
+
91
+
letprev=0,curr=1,next;
92
+
for(leti=2;i<=n;i++){
93
+
next=prev+curr;
94
+
prev=curr;
95
+
curr=next;
96
+
}
97
+
returnnext;
98
+
};
99
+
100
+
console.log(fib(5))// 5
101
+
console.log(fib(10))//55
102
+
103
+
/*
104
+
Question 6: Missing Number
105
+
106
+
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
107
+
*/
108
+
109
+
letmissingNumber=function(nums){
110
+
letsum=0;
111
+
for(leti=0;i<nums.length;i++){
112
+
sum+=nums[i];
113
+
}
114
+
returnnums.length*(nums.length+1)/2-sum;
115
+
};
116
+
117
+
/*
118
+
One Line Solution:
119
+
120
+
let missingNumber = (nums) => nums.length*(nums.length+1)/2 - nums.reduce((acc, num) => num + acc);
0 commit comments