Skip to content

Commit 6445fad

Browse files
Sync LeetCode submission Runtime - 703 ms (5.02%), Memory - 9.2 MB (10.39%)
1 parent 854e084 commit 6445fad

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<p>You are given an integer <code>n</code>.</p>
2+
3+
<p>Return the <strong>total</strong> number of commas used when writing all integers from <code>[1, n]</code> (inclusive) in <strong>standard</strong> number formatting.</p>
4+
5+
<p>In <strong>standard</strong> formatting:</p>
6+
7+
<ul>
8+
<li>A comma is inserted after <strong>every three</strong> digits from the right.</li>
9+
<li>Numbers with <strong>fewer</strong> than 4 digits contain no commas.</li>
10+
</ul>
11+
12+
<p>&nbsp;</p>
13+
<p><strong class="example">Example 1:</strong></p>
14+
15+
<div class="example-block">
16+
<p><strong>Input:</strong> <span class="example-io">n = 1002</span></p>
17+
18+
<p><strong>Output:</strong> <span class="example-io">3</span></p>
19+
20+
<p><strong>Explanation:</strong></p>
21+
22+
<p>The numbers <code>&quot;1,000&quot;</code>, <code>&quot;1,001&quot;</code>, and <code>&quot;1,002&quot;</code> each contain one comma, giving a total of 3.</p>
23+
</div>
24+
25+
<p><strong class="example">Example 2:</strong></p>
26+
27+
<div class="example-block">
28+
<p><strong>Input:</strong> <span class="example-io">n = 998</span></p>
29+
30+
<p><strong>Output:</strong> <span class="example-io">0</span></p>
31+
32+
<p><strong>Explanation:</strong></p>
33+
34+
<p>All numbers from 1 to 998 have fewer than four digits. Therefore, no commas are used.</p>
35+
</div>
36+
37+
<p>&nbsp;</p>
38+
<p><strong>Constraints:</strong></p>
39+
40+
<ul>
41+
<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>
42+
</ul>
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public:
3+
int countCommas(int n) {
4+
auto commas = [](int x) {
5+
string s = to_string(x);
6+
return (s.size() - 1) / 3;
7+
};
8+
9+
int ans = 0;
10+
for (int i=1; i<=n; i++) {
11+
ans += commas(i);
12+
}
13+
14+
return ans;
15+
}
16+
};

0 commit comments

Comments
 (0)