Rotated Digits | String Problem | LeetCode 788

4 years ago Lalit Bhagtani 0

Problem Statement

A number N is a good number if after rotating each digit individually by 180 degrees, we get a valid number which is different from N.

A number is valid if each digit remains a digit after rotation. following is the list of digits and its rotated state.

0  --> 0
1  -->  1
2  --> 5
3  --> Invalid
4  --> Invalid
5  --> 2
6  --> 9
7  --> Invalid
8  --> 8
9  --> 6

Given a positive number N, find out how many numbers from 1 to N are good numbers.

Example 

Rotated Digits

Input :- N = 12
Output :- 5
Input :- N = 21
Output :- 10

Solution

This problem can be solved in following steps :-

  1. Check each number from 1 to N.
  2. Check step 3 and 4 for each digit of the number.
  3. If number is made up of 3, 4 or 7 digit then number is not a good number.
  4. If number is made up of 2, 5, 6 or 9 digit (at least one occurrence of any one digit) and step 3 is false, then number is a good number.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		int result = main.rotatedDigits(21);
		System.out.println(result);
	}
	
	/* Solution */
	public int rotatedDigits(int N) {
        
        boolean isGood = false;
        int num = 1, count = 0, x, rem;
        while(num <= N){ 
            isGood = false;
            x = num; 
            while(x > 0){
                
                rem = x %10;
                x = x /10;
                if(rem == 3 || rem == 4 || rem == 7){
                    isGood = false;
                    break;
                }else if(rem == 2 || rem == 5 || rem == 6 || rem == 9){
                    isGood = true;
                }                
            }
            
            if(isGood){
                count++;
            }
            num++;
        }
        return count;
    }
}

Result

10

Similar Post

  1. Ransom Note
  2. Single Row Keyboard
  3. Alphabet Board Path

That’s all for Rotated Digits in Java, If you liked it, please share your thoughts in a comments section and share it with others too.