Write a program to find the given number is Armstrong number or not
package com.java2novice.algos;
public class MyArmstrongNumber
{
public boolean isArmstrongNumber(int number)
{
int tmp = number;
int noOfDigits =
String.valueOf(number).length();
int sum = 0;
int div = 0;
while(tmp
> 0)
{
div
= tmp % 10;
int temp = 1;
for(int i=0;i
{
temp
*= div;
}
sum
+= temp;
tmp
= tmp/10;
}
if(number
== sum)
{
return true;
}
else
{
return false;
}
}
public static void main(String a[])
{
MyArmstrongNumber
man = new MyArmstrongNumber();
System.out.println("Is
371 Armstrong number? "+man.isArmstrongNumber(371));
System.out.println("Is
523 Armstrong number? "+man.isArmstrongNumber(523));
System.out.println("Is
153 Armstrong number? "+man.isArmstrongNumber(153));
}
}
Write a program to convert binary to decimal number
package com.java2novice.algos;
public class BinaryToDecimal
{
public int getDecimalFromBinary(int binary)
{
int decimal = 0;
int power = 0;
while(true){
if(binary
== 0)
{
break;
}
else
{
int tmp = binary%10;
decimal
+= tmp*Math.pow(2, power);
binary
= binary/10;
power++;
}
}
return decimal;
}
public static void main(String a[])
{
BinaryToDecimal
bd = new BinaryToDecimal();
System.out.println("11
===> "+bd.getDecimalFromBinary(11));
System.out.println("110
===> "+bd.getDecimalFromBinary(110));
System.out.println("100110
===> "+bd.getDecimalFromBinary(100110));
}
}
Write a program to check the given number is binary number or not
package com.java2novice.algos;
public class MyBinaryCheck
{
public boolean isBinaryNumber(int binary)
{
boolean status = true;
while(true)
{
if(binary
== 0)
{
break;
}
else
{
int tmp = binary%10;
if(tmp
> 1)
{
status
= false;
break;
}
binary
= binary/10;
}
}
return status;
}
public static void main(String a[])
{
MyBinaryCheck
mbc = new MyBinaryCheck();
System.out.println("Is
1000111 binary? :"+mbc.isBinaryNumber(1000111));
System.out.println("Is
10300111 binary? :"+mbc.isBinaryNumber(10300111));
}
}
Write a program for Bubble Sort in java
package com.java2novice.algos;
public class MyBubbleSort
{
public static void bubble_srt(int array[])
{
int n = array.length;
int k;
for (int m = n; m >= 0; m--)
{
for (int i = 0; i < n - 1;
i++)
{
k
= i + 1;
if (array[i] >
array[k])
{
swapNumbers(i,
k, array);
}
}
printNumbers(array);
}
}
private static void swapNumbers(int i, int j, int[] array)
{
int temp;
temp
= array[i];
array[i]
= array[j];
array[j]
= temp;
}
private static void printNumbers(int[] input)
{
for (int i = 0; i <
input.length; i++)
{
System.out.print(input[i]
+ ", ");
}
System.out.println("\n");
}
public static void main(String[] args)
{
int[]
input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
bubble_srt(input);
}
}
No comments:
Post a Comment