1)print the letters only in a string
Eg 1: Input: sabari10
output:sabari
program
import java.util.*;
public class Abc {
public static void main(String[] args) {
String a,b="";
int i;
Scanner sc=new Scanner(System.in);
a=sc.next();
for(i=0;i<a.length();i++)
{
if(a.charAt(i)>='0' && a.charAt(i)<='9')
{
continue;
}
b+=a.charAt(i);
}
System.out.println(b);
}
}
2)integer to binary
input
10
output
1010
import java.util.*;
public class Abc {
public static void main(String[] args) {
int a;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
System.out.println(Integer.toBinaryString(a));
}
}
3)count the character occurance in string
input
sab
output
s-1
a-1
b-1
import java.util.*;
public class Abc {
public static void main(String[] args) {
String a;
Scanner sc=new Scanner(System.in);
int count=0;
a=sc.next();
char b[]=a.toCharArray();
for(int i=0;i<b.length;i++)
{
for(int j=0;j<b.length;j++)
{
if(b[i]==b[j])
{
count++;
}
}
System.out.println(b[i]+""+count);
count=0;
}
}
}
4)
array find the prime number
example
input
5
4 6 9 3 7
output
3 7
import java.util.*;
public class Abc {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n;
n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(int i=0;i<a.length;i++)
{
if(a[i]%2!=0 && a[i]%3!=0 && a[i]%5!=0 && a[i]%7!=0 )
{
System.out.println(a[i]);
}
else if(a[i]==2 || a[i]==3 || a[i]==5 || a[i]==7 )
{
System.out.println(a[i]);
}
}
}
}
5)
Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8}
Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8}
Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8}
Output: arr3[] = {4, 5, 7, 8, 8, 9}
import java.util.*;
public class Abc {
public static void main(String[] args) {
int a[] = {1, 3, 5, 7};
int b[] = {2, 4, 6, 8};
int n1 = a.length;
int n2 = b.length;
int c[] = new int[n1 + n2];
int i=0,j=0,k=0;
for(i=0;i<n1;i++)
{
c[k++]=a[i];
}
for(j=0;j<n2;j++)
{
c[k++]=b[j];
}
Arrays.sort(c);
for(i=0;i<c.length;i++)
{
System.out.println(c[i]);
}
}
}
6)
Oddly Even Problem Statement
Given a maximum of 100 digit numbers as input, find the difference between the sum of odd and even position digits
Test Cases
Case 1
• Input: 4567
• Expected Output: 2
Explanation : Odd positions are 4 and 6 as they are pos: 1 and pos: 3, both have sum 10. Similarly, 5 and 7 are at even positions pos: 2 and pos: 4 with sum 12. Thus, difference is 12 – 10 = 2
Case 2
• Input: 5476
• Expected Output: 2
Case 3
• Input: 9834698765123
• Expected Output: 1
import java.util.*;
public class Abc {
public static void main(String[] args) {
int a,c1=0,c2=0,pos=1;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
while(a!=0)
{
int b=a%10;
if(pos%2==0)
{
c1=c1+b;
}
else
{
c2=c2+b;
}
a=a/10;
pos++;
}
System.out.println(Math.abs(c1-c2));
}
}
No comments:
Post a Comment