import java.util.ArrayList;
import java.util.List;
public class DuplicateNumber {
public int findDuplicateNumber(List
int highestNumber = numbers.size() - 1;
int total = getSum(numbers);
int duplicate = total - (highestNumber*(highestNumber+1)/2);
return duplicate;
}
public int getSum(List
int sum = 0;
for(int num:numbers){
sum += num;
}
return sum;
}
public static void main(String a[]){
List
for(int i=1;i<30;i++){
numbers.add(i);
}
//add duplicate number into the list
numbers.add(22);
DuplicateNumber dn = new DuplicateNumber();
System.out.println("Duplicate Number: "+dn.findDuplicateNumber(numbers));
}
}
Java Programs
List of java Programs
1.Program: Find out duplicate number between 1 to N numbers.
import java.util.ArrayList;
import java.util.List;
public class DuplicateNumber {
public int findDuplicateNumber(List
int highestNumber = numbers.size() - 1;
int total = getSum(numbers);
int duplicate = total - (highestNumber*(highestNumber+1)/2);
return duplicate;
}
public int getSum(List
int sum = 0;
for(int num:numbers){
sum += num;
}
return sum;
}
public static void main(String a[]){
List
for(int i=1;i<30;i++){
numbers.add(i);
}
//add duplicate number into the list
numbers.add(22);
DuplicateNumber dn = new DuplicateNumber();
System.out.println("Duplicate Number: "+dn.findDuplicateNumber(numbers));
}
}
2.Program: Find out middle index where sum of both ends are equal.
public class FindMiddleIndex {
public static int findMiddleIndex(int[] numbers) throws Exception {
int endIndex = numbers.length - 1;
int startIndex = 0;
int sumLeft = 0;
int sumRight = 0;
while (true) {
if (sumLeft > sumRight) {
sumRight += numbers[endIndex--];
} else {
sumLeft += numbers[startIndex++];
}
if (startIndex > endIndex) {
if (sumLeft == sumRight) {
break;
} else {
throw new Exception(
"Please pass proper array to match the requirement");
}
}
}
return endIndex;
}
public static void main(String a[]) {
int[] num = { 2, 4, 4, 5, 4, 1 };
try {
System.out.println("Starting from index 0, adding numbers till index "
+ findMiddleIndex(num) + " and");
System.out.println("adding rest of the numbers can be equal");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
public class FindMiddleIndex {
public static int findMiddleIndex(int[] numbers) throws Exception {
int endIndex = numbers.length - 1;
int startIndex = 0;
int sumLeft = 0;
int sumRight = 0;
while (true) {
if (sumLeft > sumRight) {
sumRight += numbers[endIndex--];
} else {
sumLeft += numbers[startIndex++];
}
if (startIndex > endIndex) {
if (sumLeft == sumRight) {
break;
} else {
throw new Exception(
"Please pass proper array to match the requirement");
}
}
}
return endIndex;
}
public static void main(String a[]) {
int[] num = { 2, 4, 4, 5, 4, 1 };
try {
System.out.println("Starting from index 0, adding numbers till index "
+ findMiddleIndex(num) + " and");
System.out.println("adding rest of the numbers can be equal");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
3.Program: Write a program to reverse a number.
public class NumberReverse {
public int reverseNumber(int number){
int reverse = 0;
while(number != 0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
NumberReverse nr = new NumberReverse();
System.out.println("Result: "+nr.reverseNumber(17868));
}
}
public class NumberReverse {
public int reverseNumber(int number){
int reverse = 0;
while(number != 0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
NumberReverse nr = new NumberReverse();
System.out.println("Result: "+nr.reverseNumber(17868));
}
}
4.Program: Write a program to find perfect number or not.
public class IsPerfectNumber {
public boolean isPerfectNumber(int number){
int temp = 0;
for(int i=1;i<=number/2;i++){
if(number%i == 0){
temp += i;
}
}
if(temp == number){
System.out.println("It is a perfect number");
return true;
} else {
System.out.println("It is not a perfect number");
return false;
}
}
public static void main(String a[]){
IsPerfectNumber ipn = new IsPerfectNumber();
System.out.println("Is perfect number: "+ipn.isPerfectNumber(28));
}
}
public class IsPerfectNumber {
public boolean isPerfectNumber(int number){
int temp = 0;
for(int i=1;i<=number/2;i++){
if(number%i == 0){
temp += i;
}
}
if(temp == number){
System.out.println("It is a perfect number");
return true;
} else {
System.out.println("It is not a perfect number");
return false;
}
}
public static void main(String a[]){
IsPerfectNumber ipn = new IsPerfectNumber();
System.out.println("Is perfect number: "+ipn.isPerfectNumber(28));
}
}
5.Program: Write a program to find out duplicate characters in a string.
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class DuplicateCharsInString {
public void findDuplicateChars(String str){
Map
char[] chrs = str.toCharArray();
for(Character ch:chrs){
if(dupMap.containsKey(ch)){
dupMap.put(ch, dupMap.get(ch)+1);
} else {
dupMap.put(ch, 1);
}
}
Set
for(Character ch:keys){
if(dupMap.get(ch) > 1){
System.out.println(ch+"--->"+dupMap.get(ch));
}
}
}
public static void main(String a[]){
DuplicateCharsInString dcs = new DuplicateCharsInString();
dcs.findDuplicateChars("WorldFort");
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class DuplicateCharsInString {
public void findDuplicateChars(String str){
Map
char[] chrs = str.toCharArray();
for(Character ch:chrs){
if(dupMap.containsKey(ch)){
dupMap.put(ch, dupMap.get(ch)+1);
} else {
dupMap.put(ch, 1);
}
}
Set
for(Character ch:keys){
if(dupMap.get(ch) > 1){
System.out.println(ch+"--->"+dupMap.get(ch));
}
}
}
public static void main(String a[]){
DuplicateCharsInString dcs = new DuplicateCharsInString();
dcs.findDuplicateChars("WorldFort");
}
}
6.Program: Write a program to find top two maximum numbers in a array.
public class TwoMaxNumbers {
public void printTwoMaxNumbers(int[] nums){
int maxOne = 0;
int maxTwo = 0;
for(int n:nums){
if(maxOne < n){
maxTwo = maxOne;
maxOne =n;
} else if(maxTwo < n){
maxTwo = n;
}
}
System.out.println("First Max Number: "+maxOne);
System.out.println("Second Max Number: "+maxTwo);
}
public static void main(String a[]){
int num[] = {5,34,78,2,45,1,99,23};
TwoMaxNumbers tmn = new TwoMaxNumbers();
tmn.printTwoMaxNumbers(num);
}
}
public class TwoMaxNumbers {
public void printTwoMaxNumbers(int[] nums){
int maxOne = 0;
int maxTwo = 0;
for(int n:nums){
if(maxOne < n){
maxTwo = maxOne;
maxOne =n;
} else if(maxTwo < n){
maxTwo = n;
}
}
System.out.println("First Max Number: "+maxOne);
System.out.println("Second Max Number: "+maxTwo);
}
public static void main(String a[]){
int num[] = {5,34,78,2,45,1,99,23};
TwoMaxNumbers tmn = new TwoMaxNumbers();
tmn.printTwoMaxNumbers(num);
}
}
7.Program: Write a program to print fibonacci series.
public class MyFibonacci {
public static void main(String a[]){
int febCount = 15;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++){
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++){
System.out.print(feb[i] + " ");
}
}
}
public class MyFibonacci {
public static void main(String a[]){
int febCount = 15;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++){
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++){
System.out.print(feb[i] + " ");
}
}
}
8.Program: Write a program to find common elements between two arrays.
public class CommonElementsInArray {
public static void main(String a[]){
int[] arr1 = {4,7,3,9,2};
int[] arr2 = {3,2,12,9,40,32,4};
for(int i=0;i
System.out.println(arr1[i]);
}
}
}
}
}
public class CommonElementsInArray {
public static void main(String a[]){
int[] arr1 = {4,7,3,9,2};
int[] arr2 = {3,2,12,9,40,32,4};
for(int i=0;i
System.out.println(arr1[i]);
}
}
}
}
}
9.Program: How to swap two numbers without using temporary variable.
public class MySwapingTwoNumbers {
public static void main(String a[]){
int x = 10;
int y = 20;
System.out.println("Before swap:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
x = x+y;
y=x-y;
x=x-y;
System.out.println("After swap:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
}
}
public class MySwapingTwoNumbers {
public static void main(String a[]){
int x = 10;
int y = 20;
System.out.println("Before swap:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
x = x+y;
y=x-y;
x=x-y;
System.out.println("After swap:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
}
}
10.Program: Write a program to find the given number is Armstrong number or not.
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
}
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));
}
}
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
}
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));
}
}
11.Program: Write a program for Bubble Sort in java.
public class MyBubbleSort {
// logic to sort the elements
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);
}
}
public class MyBubbleSort {
// logic to sort the elements
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);
}
}
12.Program: Write a program for Insertion Sort in java.
public class MyInsertionSort {
public static void main(String[] args) {
int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
insertionSort(input);
}
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 insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
printNumbers(array);
}
}
}
public class MyInsertionSort {
public static void main(String[] args) {
int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
insertionSort(input);
}
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 insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
printNumbers(array);
}
}
}
13.Program: Write a program to find the sum of the first 1000 prime numbers.
public class Main {
public static void main(String args[]){
int number = 2;
int count = 0;
long sum = 0;
while(count < 1000){
if(isPrimeNumber(number)){
sum += number;
count++;
}
number++;
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
for(int i=2; i<=number/2; i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
public class Main {
public static void main(String args[]){
int number = 2;
int count = 0;
long sum = 0;
while(count < 1000){
if(isPrimeNumber(number)){
sum += number;
count++;
}
number++;
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
for(int i=2; i<=number/2; i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
14.Program: Find longest substring without repeating characters.
import java.util.HashSet;
import java.util.Set;
public class MyLongestSubstr {
private Set
private int finalSubStrSize = 0;
public Set
//reset instance variables
subStrList.clear();
finalSubStrSize = 0;
// have a boolean flag on each character ascii value
boolean[] flag = new boolean[256];
int j = 0;
char[] inputCharArr = input.toCharArray();
for (int i = 0; i < inputCharArr.length; i++) {
char c = inputCharArr[i];
if (flag[c]) {
extractSubString(inputCharArr,j,i);
for (int k = j; k < i; k++) {
if (inputCharArr[k] == c) {
j = k + 1;
break;
}
flag[inputCharArr[k]] = false;
}
} else {
flag[c] = true;
}
}
extractSubString(inputCharArr,j,inputCharArr.length);
return subStrList;
}
private String extractSubString(char[] inputArr, int start, int end){
StringBuilder sb = new StringBuilder();
for(int i=start;i
}
String subStr = sb.toString();
if(subStr.length() > finalSubStrSize){
finalSubStrSize = subStr.length();
subStrList.clear();
subStrList.add(subStr);
} else if(subStr.length() == finalSubStrSize){
subStrList.add(subStr);
}
return sb.toString();
}
public static void main(String a[]){
MyLongestSubstr mls = new MyLongestSubstr();
System.out.println(mls.getLongestSubstr("java2novice"));
System.out.println(mls.getLongestSubstr("java_language_is_sweet"));
System.out.println(mls.getLongestSubstr("java_java_java_java"));
System.out.println(mls.getLongestSubstr("abcabcbb"));
}
}
import java.util.HashSet;
import java.util.Set;
public class MyLongestSubstr {
private Set
private int finalSubStrSize = 0;
public Set
//reset instance variables
subStrList.clear();
finalSubStrSize = 0;
// have a boolean flag on each character ascii value
boolean[] flag = new boolean[256];
int j = 0;
char[] inputCharArr = input.toCharArray();
for (int i = 0; i < inputCharArr.length; i++) {
char c = inputCharArr[i];
if (flag[c]) {
extractSubString(inputCharArr,j,i);
for (int k = j; k < i; k++) {
if (inputCharArr[k] == c) {
j = k + 1;
break;
}
flag[inputCharArr[k]] = false;
}
} else {
flag[c] = true;
}
}
extractSubString(inputCharArr,j,inputCharArr.length);
return subStrList;
}
private String extractSubString(char[] inputArr, int start, int end){
StringBuilder sb = new StringBuilder();
for(int i=start;i
}
String subStr = sb.toString();
if(subStr.length() > finalSubStrSize){
finalSubStrSize = subStr.length();
subStrList.clear();
subStrList.add(subStr);
} else if(subStr.length() == finalSubStrSize){
subStrList.add(subStr);
}
return sb.toString();
}
public static void main(String a[]){
MyLongestSubstr mls = new MyLongestSubstr();
System.out.println(mls.getLongestSubstr("java2novice"));
System.out.println(mls.getLongestSubstr("java_language_is_sweet"));
System.out.println(mls.getLongestSubstr("java_java_java_java"));
System.out.println(mls.getLongestSubstr("abcabcbb"));
}
}
15.Program:To check whether a number is ISBN number or not.
import java.io.*;
class ISBN
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a 10 digit code : ");
String s=br.readLine();
int len=s.length();
if(len!=10)
System.out.println("Output : Invalid Input");
else
{
char ch;
int dig=0, sum=0, k=10;
for(int i=0; i
ch=s.charAt(i);
if(ch=='X')
dig=10;
else
dig=ch-48;
sum=sum+dig*k;
k--;
}
/*Alternate Code which can be used instead of the above code
String ch;
int dig=0, sum=0, k=10;
for(int i=0; i
ch=Character.toString(s.charAt(i));
if(ch.equalsIgnoreCase("X"))
dig=10;
else
dig=Integer.parseInt(ch);
sum=sum+dig*k;
k--;
*/
System.out.println("Output : Sum = "+sum);
if(sum%11==0)
System.out.println("Leaves No Remainder - Valid ISBN Code");
else
System.out.println("Leaves Remainder - Invalid ISBN Code");
}
}
}
import java.io.*;
class ISBN
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a 10 digit code : ");
String s=br.readLine();
int len=s.length();
if(len!=10)
System.out.println("Output : Invalid Input");
else
{
char ch;
int dig=0, sum=0, k=10;
for(int i=0; i
ch=s.charAt(i);
if(ch=='X')
dig=10;
else
dig=ch-48;
sum=sum+dig*k;
k--;
}
/*Alternate Code which can be used instead of the above code
String ch;
int dig=0, sum=0, k=10;
for(int i=0; i
ch=Character.toString(s.charAt(i));
if(ch.equalsIgnoreCase("X"))
dig=10;
else
dig=Integer.parseInt(ch);
sum=sum+dig*k;
k--;
*/
System.out.println("Output : Sum = "+sum);
if(sum%11==0)
System.out.println("Leaves No Remainder - Valid ISBN Code");
else
System.out.println("Leaves Remainder - Invalid ISBN Code");
}
}
}
16.Program:To find the sum of first and last digit of the number input by the user.
class intet
{
public static void main(int l)
{
String j=""+l;//converting the number to string
char m = ' ';
char k=' ';
int b = j.length();//finding the length of the string.
char ch = j.charAt(0);
m = ch;//first digit of that number.
char ch1 = j.charAt(b-1);//last digit of that number
k = ch1;
String h1 =""+m;//changing the digit to string.
String h2 =""+k;
int n1=Integer.parseInt(h1);//now changing the string to interger.
int n2=Integer.parseInt(h2);
int sum = n1+n2;//sum of both digits.
System.out.println(sum);
}
}
class intet
{
public static void main(int l)
{
String j=""+l;//converting the number to string
char m = ' ';
char k=' ';
int b = j.length();//finding the length of the string.
char ch = j.charAt(0);
m = ch;//first digit of that number.
char ch1 = j.charAt(b-1);//last digit of that number
k = ch1;
String h1 =""+m;//changing the digit to string.
String h2 =""+k;
int n1=Integer.parseInt(h1);//now changing the string to interger.
int n2=Integer.parseInt(h2);
int sum = n1+n2;//sum of both digits.
System.out.println(sum);
}
}