LeetCode – Rotated Digits (Java)

X is a good number if after rotating EACH digit individually by 180 degrees, we get a valid number that is different from X. A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number.

Java Solution

public int rotatedDigits(int N) {
    int result = 0;
 
    for(int i=1; i<=N; i++){
        int j=i;
        boolean contains347 = false;
        boolean contains2569 = false;
        while(j!=0){
            int mod = j%10;
            if(mod==2||mod==5||mod==6||mod==9){
                contains2569=true;
            }
 
            if(mod==3||mod==4||mod==7){
                contains347=true;
            }
 
            j=j/10;
        }
 
        if(!contains347&&contains2569){
            result++;
        }
    }
 
    return result;
}

1 thought on “LeetCode – Rotated Digits (Java)”

Leave a Comment