用JAVA解决FizzBuzz的几种方法

用JAVA解决FizzBuzz的几种方法

编写一个程序从1到100.当遇到数字为3的倍数的时候,点击“Fizz”替代数字,5的倍数用“Buzz”代替,既是3的倍数又是5的倍数点击“FizzBuzz”。

Write a program that prints the integers from 1 to 100.

But for multiples of three print “Fizz” instead of the number, and for the multiples of five print “Buzz”.
For numbers which are multiples of both three and five print “FizzBuzz”. [1]

FizzBuzz was presented as the lowest level of comprehension required to illustrate adequacy

If/else ladder

public class FizzBuzz{
	public static void main(String[] args){
		for(int i= 1; i <= 100; i++){
			if(i % 15 == 0){
				System.out.println("FizzBuzz");
			}else if(i % 3 == 0){
				System.out.println("Fizz");
			}else if(i % 5 == 0){
				System.out.println("Buzz");
			}else{
				System.out.println(i);
			}
		}
	}
}

Concatenation

public class FizzBuzz{
	public static void main(String[] args){
		for(int i= 1; i <= 100; i++){
			String output = "";
			if(i % 3 == 0) output += "Fizz";
			if(i % 5 == 0) output += "Buzz";
			if(output.equals("")) output += i;
			System.out.println(output);
		}
	}
}

Ternary operator

public class FizzBuzz{
	public static void main(String[] args){
		for(int i= 1; i <= 100; i++){
			System.out.println(i % 15 != 0 ? i % 5 != 0 ? i % 3 != 0 ? 
			i : "Fizz" : "Buzz" : "FizzBuzz");
		}
	}
}

Recursive

public String fizzBuzz(int n){
  String s = "";
  if (n == 0)
    return s;
  if((n % 5) == 0)
    s = "Buzz" + s;
  if((n % 3) == 0)
    s = "Fizz" + s;
  if (s.equals(""))
    s = n + "";   
  return fizzBuzz(n-1) +  s;
}

Alternative Recursive

public String fizzBuzz(int n){
  return (n>0) ? fizzBuzz(n-1) + 
    (n % 15 != 0? n % 5 != 0? n % 3 != 0? (n+"") :"Fizz" : "Buzz" : "FizzBuzz") 
               : "";
}

Using an array

class FizzBuzz {
  public static void main( String [] args ) {
    for( int i = 1 ; i <= 100 ; i++ ) {
      System.out.println( new String[]{ i+"", "Fizz", "Buzz", "FizzBuzz" }[ ( i%3==0?1:0 ) + ( i%5==0?2:0 ) ]);
    }
  }
}

Lambda with Arrays

class FizzBuzz {
  public static void main( String [] args ) {
    int [] x = new int [100];
    Arrays.setAll(x, j -> j++);
    Arrays.stream(x).forEach(i -> {
        if(i == 0) return;
        String output = "";
        if(i % 3 == 0) output += "Fizz";
        if(i % 5 == 0) output += "Buzz";
        if(output.equals("")) output += i;
        System.out.println(output);
    });
  }
}

Lambda with Streams

package fizzbuzz;
 
import static java.util.stream.IntStream.rangeClosed;
 
public interface FizzBuzz {
  public static void main(String... arguments) {
    rangeClosed(1, 100)
      .mapToObj(i -> {
        if (i % (3 * 5) == 0) {
          return "FizzBuzz";
        } else if (i % 3 == 0) {
          return "Fizz";
        } else if (i % 5 == 0) {
          return "Buzz";
        } else {
          return Integer.toString(i);
        }
      })
      .forEach(System.out::println)
    ;
  }
}

发表评论

您的电子邮箱地址不会被公开。