by BehindJava

Wap to convert String of vowels and consonants into 0's and 1's and print the decimal value of the binary string in Java and Python

Home » java » Wap to convert String of vowels and consonants into 0's and 1's and print the decimal value of the binary string in Java and Python

In this tutorial, we are going to learn about implementing the above problem statement in detail.

Whenever you face, these kind of problem statements. Go with the divide and conquer approach.

  1. Initialize a String str=“hellobehindjava”.
  2. Find the vowels and consonants.
  3. Make vowels as 0’s and consonants as 1’s.
  4. Convert the 0’s and 1 ‘s to a decimal number.

Java Code

public class StringToDecimal {

	public static void main(String args[]) {
		String str = "hellobehindjava";
		char zero = '0';
		char one = '1';
		int len = str.length();
		char[] c = new char[len];
		for (int i = 0; i < len; i++) {
			if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o'
					|| str.charAt(i) == 'u') {

				c[i] = zero;
			} else {
				c[i] = one;
			}
		}
		String st = String.valueOf(c);
		System.out.println("String converted to 0's and 1's: "+st);
		int decimal = Integer.parseInt(st, 2);
		System.out.println("Binary String to decimal: "+decimal);
	}
}

Output:

String converted to 0's and 1's: 101101010111010
Binary String to decimal: 23226

Python Code

s=input("hellobehindjava")
m=[ ]
def binarytodecimal(n):
      decimal=0
      power=1
      while n>0:
           rem=n%10
           n=n//10
           decimal+=rem*power
           power=power*2
      return decimal
for i in s :
     if (i=='a' or i=='e' or i=='i' or i=='o' or i=='u' ) : 
          m.append (0)
     else :
         m.append (1)
st=" "
for i in m :
     st=st+str(i)
print(st)
print(binarytodecimal(int(st)))

Output:

hellobehindjava 101101010111010
23226