Count the Numbers from 1 to N

Solve this Problem
Easy5 min
Topics
Companies
Given a non-negative integer n, return how many numbers there are from 1 to n. The loopCounter LoopWalking i from 1 to n, incrementing a counter once per iteration. version practices the fundamental pattern of counting things with a loop — useful when what's being counted isn't already known in advance. The direct returnDirect ReturnRecognizing that the quantity being counted is already exactly n, with nothing left to compute. version is the lesson this particular problem is really teaching: sometimes the "count" a loop would produce is already sitting in a variable, and the loop is pure, provable overhead.

Test Case 1:

Input:n = 5
Output:5
Explanation:The numbers 1, 2, 3, 4, 5 — five of them.

Test Case 2:

Input:n = 1
Output:1
Explanation:Just one number.

Test Case 3:

Input:n = 0
Output:0
Explanation:No numbers to count.

Constraints

  • ◆0 ≤ n ≤ 1000000

Try the Dry Run

Approach & Solutions

Loop — Increment a CounterGood

Walk i from 1 to n, incrementing a counter once per iteration — the most literal way to answer "how many numbers are there from 1 to n": count them, one at a time.

TimeO(n)
SpaceO(1)
1class Solution { 2 public int countNumbers(int n) { 3 int count = 0; 4 for (int i = 1; i <= n; i++) { 5 count++; 6 } 7 return count; 8 } 9}
Direct Return — n Is Already the CountOptimal

The count of numbers from 1 to n is, by definition, n itself — there's nothing to loop over or tally. Counting one-by-one only ever rediscovers the value that was already given.

TimeO(1)
SpaceO(1)
1class Solution { 2 public int countNumbers(int n) { 3 return n; 4 } 5}

Related Problems