2652. Sum Multiples
Explanation
To solve this problem, we iterate through all numbers from 1 to n and check if the number is divisible by 3, 5, or 7. If the number is divisible by any of these, we add it to the sum. Finally, we return the sum as the result.
- We iterate through numbers from 1 to n
- For each number, we check if it is divisible by 3, 5, or 7
- If it is divisible by any of these, we add it to the sum
- Return the final sum as the result
Time Complexity: O(n) Space Complexity: O(1)
class Solution {
public int sumMultiples(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 || i % 5 == 0 || i % 7 == 0) {
sum += i;
}
}
return sum;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.