import java.util.Scanner; public class ConvertBinary2Decimal { public static int power(int num ,int pwr) { int res = 1; for (int i = 1; i <= pwr; i++) { res = res * num; } return res; } public static int B2D(int num) { int count = 0; int output = 0; while (num > 0) { int rem = num % 10; output = output+rem*power(2,count++); num = num / 10; } return output; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("enter the number = "); int num = sc.nextInt(); int res = B2D(num); System.out.println("the decimal equivalent of "+num+" = "+res); sc.close(); } }
Month: May 2018
Hexadecimal to Decimal Conversion
import java.util.Scanner; public class ConvertHexa2Decimal { public static int power(int num,int pwr) { int res=1; for (int i = 0; i <=pwr; i++) { res= res*num; } return res; } public static int hexToDecimal(String s1) { int c= s1.length()-1; int out=0; int count =0; while(c>0) { char ch = s1.charAt(c); if(ch>=65 && ch<=70) { out = out + (ch-55)*power(16, count++); } else if(ch>=97 && ch<=102) { out = out + (ch-87)*power(16, count++); } else if(ch>=48 && ch<=57) { out = out + (ch-48)*power(16, count++); } else { System.out.println("Invalid character"); return -1; } } return out; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number"); String s1 = sc.next(); int out = hexToDecimal(s1); System.out.println(out); sc.close(); } }
Strings: Reverse Whole word
import java.util.Scanner; public class Strings_reverseWholeWord { public static String reverse(String s1) { String s2 = ""; char ch[] = s1.toCharArray(); for (int i = 0; i < ch.length; i++) { String res = ""; while (i < ch.length && ch[i] != ' ') { res = res+ch[i]; i++; } s2 =res+" "+s2; } return s2; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the String : "); String s1 = sc.nextLine(); System.out.println(reverse(s1)); sc.close(); } }
Output:
Enter the String :
Welcome to the programming blog
blog programming the to Welcome
Strings: Reverse Each Word
import java.util.Scanner; public class Strings_reverseEachWord { public static String reverse(String s1) { String s2 = ""; char ch[] = s1.toCharArray(); for (int i = 0; i < ch.length; i++) { String res = ""; while (i < ch.length&& ch[i] != ' ' ) { res = ch[i]+res; i++; } s2 =s2+res+" "; } return s2; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the String : "); String s1 = sc.nextLine(); String s2 = reverse(s1); System.out.println(s2); sc.close(); } }
Output:
Enter the String :
welcome to programming blog!! hava a nice day
emoclew ot gnimmargorp !!golb avah a ecin yad