if (n<100) {
x = 10;
} else if (n<1000) {
x = 100;
} else if (n<10000) {
x = 1000;
} else if (n....
etc. etc.
Is there a nice concise, scalable method for this type of problem? My brain has decided to stop working.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This one might be preferable, because it’s available as a constant so it doesn’t need to be calculated each time:
It basically comes down to rounding down logarithmically.
Edit: Because a combination of
logand/often tends to result in errors, it might be a good idea to round the quotient as well (currently,Math.log(1000) / Math.LN10 === 2.9999999999999996).This rounding might result in new errors, but for ‘normal’ inputs the answer is now more often correct.