So I have to find the largest number that contains n digits. For example, if n=2, then the largestNumber = 99. This was my answer.
function largestNumber(n) {
var num = [];
n = num.length;
for(var i = 0; i < n; i++){
num[i] = "9";
};
var large = +(num.join(''));
return large;
}
Unfortunately, it returned "0". When I tried to console.log the array.
function largestNumber(n) {
var num = [];
n = num.length;
for(var i = 0; i < n; i++){
num[i] = "9";
};
return num;
}
console.log(largestNumber(2));
I got an empty array instead of ["9", "9"]. Why is my array not forming?
So I have to find the largest number that contains n digits. For example, if n=2, then the largestNumber = 99. This was my answer.
function largestNumber(n) {
var num = [];
n = num.length;
for(var i = 0; i < n; i++){
num[i] = "9";
};
var large = +(num.join(''));
return large;
}
Unfortunately, it returned "0". When I tried to console.log the array.
function largestNumber(n) {
var num = [];
n = num.length;
for(var i = 0; i < n; i++){
num[i] = "9";
};
return num;
}
console.log(largestNumber(2));
I got an empty array instead of ["9", "9"]. Why is my array not forming?
Share Improve this question asked Oct 9, 2016 at 19:44 muzzomuzzo 1211 gold badge3 silver badges9 bronze badges 7-
2
Remove
n = num.length;
. That line is pointless and discards the parameter you passed to the function by resetting it to0
. – Sebastian Simon Commented Oct 9, 2016 at 19:45 -
2
Simpler method:
function largestNumber(n) { return Math.pow(10, n) - 1; }
– Amit Commented Oct 9, 2016 at 19:51 -
Of course,
99
is not the largest number that contains exactly two digits. – georg Commented Oct 9, 2016 at 20:26 -
@georg What do you mean?
0xFF
?9e9
? – Bergi Commented Oct 9, 2016 at 20:44 - @Bergi: yep, the assignment is pretty sloppy formulated. – georg Commented Oct 10, 2016 at 9:50
4 Answers
Reset to default 4Why not use (10^n)-1 ?
Math.pow(10,n)-1
You are resetting n
to 0 by assigning it with n = num.length;
right after defining num
as an empty array. Just drop this line and you should be fine.
Using n as the power of 10 and subtracting 1 from the result gives you the correct answer for any integer value of n.
def largestNumber(n):
large = (10 ** n) -1
print(large)
largestNumber(2)
I did it like this:
function largestNumber(n) {
let number = "9";
for(let i=1;i<n;i++){
number += "9";
}
return parseInt(number);
}