Example:
1 |
n = 15, |
Conventional thinking
Title very simple multiple output n is 3 Fizz
, n is a multiple of output 5 Buzz
, n while the output 3 or 5 multiples FizzBuzz
. That is, when the determination condition, should first determine whether n is a multiple of 15, followed by determining whether a multiple of 3 or 5 to determine what output. code show as below:
1 |
class Solution { |
Here to say, as if LeetCode use the List is not required when the lead pack in the code, I tried no matter did to the first line import java.util.*;
no problem.
Below is the time and memory consumption:
Runtime: 1 ms
Memory Usage: 37.2 MB
Special ideas
Top is by %
carried out modulo operation to achieve, I saw some people think the comments section:
Generally, for a CPU operand modulo relatively inefficient, it can be avoided if a large amount of remainder operands, can improve the performance of the program.
So there will be no use %
of writing:
1 |
public class Solution { |
Below is the time and memory consumption:
Runtime: 1 ms
Memory Usage: 37.3 MB
The program requires two variables in repeated self-energizing and re-assigned to 0, you can use the following programs to reduce these operations:
1 |
public class Solution { |
下面是时间与内存的消耗:
Runtime: 1 ms
Memory Usage: 37.1 MB
补充:i+""
和String.valueOf(i)
which is better between
list.add( “” + i );
and
addStr = String.valueOf(i); list.add(addStr)?
我认为后者的写法更好,因为i+""
实际上会new一个StringBuilder去拼接i
和""
,然后再调用toString()来得到字符串。而String.valueOf(i)
在底层是调用了Integer.toString(i)
来得到字符串。