Iteration over String solution (Java)


  • 0
    Q

    Convert int to binary stirng, Iterate over the string to verify that one and only one char is 1.

    public class Solution {
        public boolean isPowerOfTwo(int n) {
            String s = Long.toBinaryString(n);
            boolean pOfTwo = false;
            for (char c : s.toCharArray()){
            	if (c - '0' == 1){
            		if (pOfTwo == false){
            			pOfTwo = true;
            		}
            		else if (pOfTwo == true){
            			return false;
            		}
            	}
            }
            return pOfTwo;
        }
    }

  • 0

    Thanks for the idea!
    But I didn't see why you use c-'0'==1 instead of c=='1'

    Besides, here's my similar idea but different solution:

        //268ms
        String n2 = Integer.toBinaryString(n);
        int i;
        for (i=n2.length()-1; i>=0 && n2.charAt(i)=='0'; i--) {}
        if (i==0) return true;
        else return false;

  • 0
    Q

    c =='1' is fine. Iterating backwards is a good idea as it simplifies logic.


Log in to reply
 

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