Nth positive number whose absolute difference of adjacent digits is at most 1 | Java program to find Nth number with absolute difference between all adjacent digits at most 1. ; Return Nth number with absolute difference between all adjacent digits at most 1. ; To store all such numbers ; Enqueue all integers from 1 to 9 in increasing order . ; Perform the operation N times so that we can get all such N numbers . ; Store the front element of queue , in array and pop it from queue . ; If the last digit of dequeued integer is not 0 , then enqueue the next such number . ; Enqueue the next such number ; If the last digit of dequeued integer is not 9 , then enqueue the next such number . ; Driver Code
import java . util . * ; class GFG { static void findNthNumber ( int N ) { int [ ] arr = new int [ N + 1 ] ; Queue < Integer > q = new LinkedList < > ( ) ; for ( int i = 1 ; i <= 9 ; i ++ ) q . add ( i ) ; for ( int i = 1 ; i <= N ; i ++ ) { arr [ i ] = q . peek ( ) ; q . remove ( ) ; if ( arr [ i ] % 10 != 0 ) q . add ( arr [ i ] * 10 + arr [ i ] % 10 - 1 ) ; q . add ( arr [ i ] * 10 + arr [ i ] % 10 ) ; if ( arr [ i ] % 10 != 9 ) q . add ( arr [ i ] * 10 + arr [ i ] % 10 + 1 ) ; } System . out . println ( arr [ N ] ) ; } public static void main ( String [ ] args ) { int N = 21 ; findNthNumber ( N ) ; } }