Reverse a number using a while loop
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}Reverse a number using for loop
int num;
for( ;num != 0; )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}Reverse a number using recursion
public static void reverseMethod(int number) {
if (number
Check prime number
int num=scan.nextInt();
for(int i=2;i
Perform binary search
public static void main(String args[])
{
int counter, num, item, array[], first, last, middle;
//To capture user input
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt(); //Creating array to store the all the numbers
array = new int[num];
System.out.println("Enter " + num + " integers");
//Loop to store each numbers in array
for (counter = 0; counter last )
System.out.println(item + " is not found.\n");}
Linear search
int counter, num, item, array[];
//To capture user input
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();
//Creating array to store the all the numbers
array = new int[num];
System.out.println("Enter " + num + " integers");
//Loop to store each numbers in array
for (counter = 0; counterFind duplicate Characters in a String
public void countDupChars(String str){
//Create a HashMap
Map map = new HashMap(); //Convert the String to char array
char[] chars = str.toCharArray(); /* logic: char are inserted as keys and their count
* as values. If map contains the char already then
* increase the value by 1
*/
for(Character ch:chars){
if(map.containsKey(ch)){
map.put(ch, map.get(ch)+1);
} else {
map.put(ch, 1);
}
} //Obtaining set of keys
Set keys = map.keySet(); /* Display count of chars if it is
* greater than 1. All duplicate chars would be
* having value greater than 1.
*/
for(Character ch:keys){
if(map.get(ch) > 1){
System.out.println("Char "+ch+" "+map.get(ch));
}
}
}Convert binary to decimal using Integer.parseInt() method
Scanner input = new Scanner( System.in );
System.out.print("Enter a binary number: ");
String binaryString =input.nextLine();
System.out.println("Output: "+Integer.parseInt(binaryString,2));Convert binary to decimal without using parseInt
public int BinaryToDecimal(int binaryNumber){
int decimal = 0;
int p = 0;
while(true){
if(binaryNumber == 0){
break;
} else {
int temp = binaryNumber%10;
decimal += temp*Math.pow(2, p);
binaryNumber = binaryNumber/10;
p++;
}
}
return decimal;
}