Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Java Code to Count Possible Decoding Of A Given Digit Sequence

Count Possible Decoding java

Count Possible Decoding Of A Given Digit Sequence

This type of questions(or similar questions) are most probably asked in Interviews. Java Code to Count Possible Decoding of a Given Digit Sequence returns the number of decodings possible for a string. Check below example for better understanding

  • String=”123″ , possible decodings are
    • 1,2,3
    • 1,23
    • 12,3

Algorithm:-

  • Step 1: Start
  • Step 2: input given
  • Step 3: Set count = 0
  • Step 4: If the last number is not a zero, then return for the next remaining (n-1) numbers and add the results then to the total count.
  • Step 5: If the last two digits form a valid variable (or smaller than 27), return for the remaining (n-2) numbers and add the outcome to the total calculation.
  •  Step 6: Stop

Java Code:

import java.io.*;
class PREPINSTA{
    public static int cnt_decoding_digits(char[] dig, int a)
    {
        int cnt[] = new int[a+ 1];
         cnt[0] = 1;
         cnt[1] = 1;
    
         for (int k = 2; k <= a; k++
         { 
             cnt[k] = 0
             cnt[k] = cnt[k-1];
             if (dig[k-2] == ‘1’ || (dig[k-2] == ‘2’ && dig[k-1] < ‘7’) )
                  cnt[k] += cnt[k-2];
         }
         return cnt[a];
    }
    public static void main (String[] args) {
       String s=“123”;
       char[] dig= s.toCharArray();
       System.out.println(cnt_decoding_digits(dig, 6));
        }
    }

Output:

3