Java: One line solution


  • 2
    C
     public int bulbSwitch(int n) {
            return (int)Math.sqrt(n);
        }

  • -5
    J

    package solution;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;

    public class BulbSwitchSolution {

    public static void main(String[] args) {
    	// First Take input from user for n
    	Scanner user_input = new Scanner(System.in);
    	System.out.println("Enter an integer");
    	int n = user_input.nextInt();
    	System.out.println("You entered integer " + n);
    	
    	// Initialize to 0 or OFF
    
    	List<Integer> list = new ArrayList<Integer>();
    	for (int i = 1; i <= n + 1; i++) {
    		list.add(0);
    
    	}
    
    	System.out.println("size is " + list.size());
    
    	for (int j = 1; j <= n; j++) {
    		System.out.print(list.get(j));
    	}
    	System.out.println();
    	
    	
    
    	for (int i = 1; i <= n; i++) {
    		
    		// For 1st Iteration toggle to 1
    		if (i == 1) {
    			for (int j = 1; j <= n; j++) {
    				list.set(j, 1);
    			}
    		}
    		
    		for (int j = 1; j <= n; j++) {
    			System.out.print(list.get(j));
    		}
    		
    		System.out.println();
    		
    		switchBulb(i + 1, n, list);
    		
    		for (int j = 1; j <= n; j++) {
    			System.out.print(list.get(j));
    		}
    		System.out.println();
    	}
    	int count = 0;
    	for (int i = 1; i <= n; i++) {
    		if (list.get(i) == 1) {
    			count++;
    		}
    
    	}
    	System.out.println("count of ON " + count);
    	user_input.close();
    }
    
    private static void switchBulb(int i, int n, List<Integer> list) {
    	System.out.println("n is " + n + "i is: " + i);
    	for (int j = i; j <= n; j++) {
    		if (j % i == 0) {
    			if (list.get(j) == 1) {
    				list.set(j, 0);
    			} else {
    				list.set(j, 1);
    			}
    
    		}
    	}
    
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.