8.SQL Query to Count odd and even digits in a number

Author: neptune | 24th-Apr-2022
🏷️ #SQL #Hackerrank

Count odd and even digits in a number

Problem Statement : Write a query that counts odd and even digits in a number.

Sample format is described as follows:

Example 1.

Input : 123456

Output : Odd digits = 3

                Even digits = 3


Example 2.

Input : 6543

Output : Odd digits = 2

                Even digits = 2






Solution :

For this challenge, we must:

  1.  We will iterate the number and check the digits one by one, if it is odd or even.


Query :

DECLARE

  num NUMBER := 123456;

  len VARCHAR2(20);

  count1 NUMBER(5) :=0;

  count2 NUMBER(5) := 0;

BEGIN

  FOR i IN 1..Length(num)

    LOOP

      len := Substr(num, i, 1);

        IF mod(len, 2) != 0 THEN

          count1 :=  count1+1;

        ELSE 

          count2 :=count2+1;

        END IF;

    END LOOP;


dbms_output.Put_line('Odd Digits: ' || cnt1);

dbms_output.Put_line('Even Digits: ' || cnt2);


END;






Output:

Odd Digits: 3

Even Digits: 3


Hope you learn something !!!

If you have any questions let me know in the comment section.