目录
选择题
1.
最终类被 final 修饰,不能被继承
2.
默认是包访问权限。
3.
这个直接看就好了。
4.
boolean 类型不能进行强制类型转换。
byte 范围是 -128 ~ 127
编程题
1. 不要二
本质上就是初中生计算题,不要被题目吓怕。
代码实现:
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int a = in.nextInt();
int b = in.nextInt();
int[][] arr = new int[a][b];
int count = getCount(arr, a, b);
System.out.println(count);
}
}
public static int getCount(int[][] arr, int a, int b) {
int count = 0;
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
// 没放蛋糕
if (arr[i][j] == 0) {
arr[i][j] = 1;
count++;
if (i + 2 < a) {
arr[i + 2][j] = 1;
}
if (j + 2 < b) {
arr[i][j + 2] = 1;
}
}
}
}
return count;
}
}
2. 把字符串转换成整数
很简单,就是遍历字符串,然后先判断第一个字母是否是 +- 号,是的话就标记一下,然后从符号后截取掉字符串,然后遍历,看看是否是数字,是数字就加上去,不是数字就返回 0,牛客网例子比较少,所以不用考虑超过 int 的情况(试过了,不会有溢出的情况
以前写的能AC代码:
import java.util.*;
public class Solution {
public int StrToInt(String str) {
if(str == null||str.length() == 0){
return 0;
}
char[] arr = str.toCharArray();
int flg = 1;
if(arr[0]=='+'){
arr[0] = '0';
}
if(arr[0]=='-'){
arr[0] = '0';
flg = -1;
}
long sum = 0;
for(int i = 0;i<arr.length;i++){
if(arr[i]>='0'&&arr[i]<='9'){
sum = sum * 10 + arr[i] - '0';
}else{
return 0;
}
}
return flg * (int)sum;
}
}
不能 AC 代码,虽然现在没法验证正确性,但我感觉应该差不多,和我之前写的一摸一样:
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
int ret = getValue(str);
System.out.println(ret);
}
}
public static int getValue(String str) {
// 1. 把输入的字符串的引号去掉
str = str.substring(1, str.length() - 1);
int sum = 0;
int flag = 1;
if (str == null || str.isEmpty()) return 0;
// 符号判断
if (str.charAt(0) == '+') {
str = str.substring(1);
flag = 1;
}
if (str.charAt(0) == '-') {
str = str.substring(1);
flag = -1;
}
for (int i = 0; i < str.length(); i++) {
// 是数字
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
sum = sum * 10 + str.charAt(i) - '0';
} else {
return 0;
}
}
return sum * flag;
}
}