JAVA基础算法题
(一)
统计从1到N的整数中,所有立方值的平方根为整数的数的格式 输入说明:整数N(N<10000) 输出说明:符合条件的数的个数,如4^3= 64 = 8^2 输入样例:10 输出样例:3 (说明:样例中符合条件的3个数是1、4、9)
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int N = sc.nextInt();
int count=0;
for(int i=1;i<=N;i++){
double pow = Math.pow(i, 3);
double sqrt = Math.sqrt(pow);
if((int)sqrt==sqrt){
count++;
}
}
System.out.println(count++);
}
}
(二)
给出长度N的各不相同整数组成的数组,求解2个数相加为M的情况个数 输入说明:第一行,数组中元素个数N(N<1000),和值M;第二行,N个数组元素 输出样例:8 10 1 4 2 5 3 19 8 6 输出样例:2
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int N = sc.nextInt();
int M=sc.nextInt();
int count=0;
sc.nextLine();
int[] arr=new int[N];
for(int i=0;i<N;i++){
arr[i] = sc.nextInt();
}
for(int i=0;i<N;i++){
for(int j=i+1;j<N;j++)
if(arr[i]+arr[j]==M){
count++;
}
}
System.out.println(count);
}
}
(三)
某饮料店有两种奶茶饮料,其中一种每瓶含奶粉15g含茶粉5g,另一种每瓶含奶粉10g含茶粉10g。设某天饮料店消耗的奶粉和茶粉重量分别为x和y(单位g), 求当天饮料店两种饮料的销量。 输入说明:奶粉和茶粉的消耗量(均为整数) 输出说明:两种饮料各自销量(无解则输出:-1) 输入样例:400 300 输出样例:10 25
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int x = sc.nextInt();
int y=sc.nextInt();
//解二元一次方程组15*x + 10*y= 400 5*x + 10*y= 300
int M=(x-y)/10;
int N=(3*y-x)/20;
if(M<0){
System.out.print("不存在");
}else{
System.out.print(M+" ");
}
if(N<0){
System.out.println("不存在");
}
else{
System.out.println(N);
}
}
}
(四)
在一个由小写英文字母(a-z)组成的字符串中,查找最长子串,其头尾字母相同,且中间不包含该头尾字母,并输出最左边的该类子串。 输入说明:待处理字串(长度≤ 200) 输出说明:子串 输入样例:adfasjdoiasldhfa 输出样例:fasjdoiasldhlf
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str= sc.nextLine();
String result="";
for(int i=0;i<str.length();i++){
int start=i;
int end=str.length()-1;
while(start<end) {
if (str.charAt(start) == str.charAt(end)) {
String newstr = str.substring(start, end+1);
String substr = newstr.substring(1, newstr.length()-1);
if (substr.contains(String.valueOf(newstr.charAt(0)))) {
start++;
break;
} else {
result = result.length() > newstr.length() ? result : newstr;
break;
}
} else {
end--;
}
}
}
System.out.println(result);
}
}
(五)
某星球存在两种生物,A种生物有1个头6条腿,B种生物有3个头4条腿。来自地球的太空船刚刚在该星球降落, 突然发现一大群这两种生物组成的队伍,由于时间紧,只数了头的数量和腿的数量,请帮助宇航员分析A、B两种生物各有多少个。 输入说明:头的数量L腿的数量Z,(L,Z<=100000); 输出说明:A生物的数量B生物的数量(两个整数用一个空格隔开);输入样例:10 32输出样例:4 2
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int L = sc.nextInt();
int Z=sc.nextInt();
//解二元一次方程 x+3y=L 6x+4y=Z
int x=(3*Z-4*L)/14;
int y=(6*L-Z)/14;
System.out.println(x+" "+y);
}
}
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
二维码