备战蓝桥杯JAVA B组Day8
前言
零基础小白备战蓝桥杯第八天,刷题内容为:洛谷题单【入门3】循环结构。
P1307 [NOIP2011 普及组] 数字反转
AC代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = 0;
while (n != 0){
m = m * 10 + n % 10;
n = n/10;
}
System.out.print(m);
}
}
补充:
Java实现整数反转的方法并不唯一,本题采用除数和余数最快解决。
P1720 月落乌啼算钱(斐波那契数列)
AC代码:
import java.util.Scanner;
public class Main {
public static void main(String []args){
Scanner sc = new Scanner(System.in);
Double []f = new Double[50];
int n = sc.nextInt();
f[0] = 0.0;
f[1] = 1.0;
f[2] = 1.0;
for(int i = 3;i <= n;i++){
f[i] = f[i-1]+f[i-2];
}
System.out.printf("%.2f",f[n]);
}
}
补充:
这道题数据范围并不大,直接计算并不会超出,如果数据范围很大,则使用斐波那契数列解答。
P5724 【深基4.习5】求极差 / 最大跨度值
AC代码:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
System.out.println(arr[n-1]-arr[0]);
}
}
补充:
简单的数组输入和排序,注意数组越界。
P1420 最长连号
AC代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int count = 1;
int max = 1;
for (int i = 1; i < n; i++) {
if(arr[i] == arr[i-1] + 1) {
count++;
}else{
count = 1;
}
if(count>max){
max = count;
}
}
System.out.println(max);
}
}
补充:
注意最小的连数是1。
P1075 [NOIP2012 普及组] 质因数分解
AC代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 2;i <= Math.sqrt(n);i++){
if(n % i == 0){
int m = n / i;
System.out.print(Math.max(m,i));
}
}
}
}
补充:
使用循环模拟求解。
3705




被折叠的 条评论
为什么被折叠?



