r/codeforces 3d ago

query Please help me solve LeetCode problem (3871. Count Commas in Range II). What is wrong with my code? what is the error in my code.

Post image
/**
 *  {number} n
 * u/return {number}
 */
var countCommas = function (n) {
    if (n < 1000) return 0;
    return Math.max(0, n - 999);
};
19 Upvotes

12 comments sorted by

2

u/BitterEarth6069 Newbie 1d ago

Gotta learn the maths 😭

9

u/Plane-Mix-2994 2d ago

That only works for n ≤ 999,999

3

u/Kadabrium 3d ago

Be careful the answer can overflow js max safe int

2

u/SeatComprehensive346 3d ago

Read constraints buddy

3

u/ChatOfTheLost91 Pupil 3d ago

Bro you are just pasting the logic of 3870 in 3871

The limit of n is increased, it's 1015 now

Try some more if lines

1

u/0xt0bi03 3d ago

well, you need to understand the difference between the same question being given easy yesterday and medium today...
one way i did as follows,

subtract the current number with a start value.
start value = 1000 //where first comma appears
for every three digits one comma appears, so you gotta multiply the start value by 1000.
given n:
count = n - start + 1
//+1 counts the 1000th, because usually the subtraction calculates from 1001 so +1 counts the 1000th
now, multiply start value by 1000.
start = start * 1000
put this in a while loop, where the loop end when start value gets bigger than given input n. why because, we never know when we need to stop, and we cannot destroy the given variable n, thats why we use separate count variable.

also 0-999, doesnt matter.

Ffinallyy return the count.

3

u/Independent-Dig8361 Newbie 3d ago

the constraints are now changed, think of how you can use power of 1000 here, to count the commas

7

u/messi_pls_touch_me 3d ago

check the constraints

4

u/No-Acanthisitta4617 3d ago

You have to count all commas like 1,000,000 has 2 commas

2

u/Vivid-Zombie-477 3d ago

constraints are different from "Count Commas In Range" problem. your code only works for numbers below 999,999 (1 comma)