1.下面代码将输出什么内容:()
public class Test {
public static boolean isAdmin(String userId) {
return userId.toLowerCase() == "admin";
}
public static void main(String[] args) {
System.out.println(isAdmin("Admin"));
}
}//false
//toLowerCase():是重新创建了一个对象
2.阅读如下代码。 请问,对语句行 test.hello(). 描述正确的有()
class Test {
public static void hello() {
System.out.println("hello");
}
}
public class MyApplication {
public static void main(String[] args) {
Test test = null;
test.hello();
}
}
//可以运行成功
//结果为:hello
//但是如果hello方法没有用static修饰,则运行结果会报空指针异常
3.如下代码的输出结果是什么?
public class Test {
public int aMethod() {
static int i = 0;
i++;
return i;
}
//方法中不能有static修饰的变量
public static void main(String args[]) {
Test test = new Test();
test.aMethod();
int j = test.aMethod();
System.out.println(j);
}
}
//编译报错
4.汽水瓶
https://www.nowcoder.com/questionTerminal/fe298c55694f4ed39e256170ff2c205f
有这样一道智力题:“某商店规定:三个空汽水瓶可以换一瓶汽水。小张手上有十个空汽水瓶,她最多可以换多少瓶汽水喝?”答案是5瓶,方法如下:先用9个空瓶子换3瓶汽水,喝掉3瓶满的,喝完以后4个空瓶子,用3个再换一瓶,喝掉这瓶满的,这时候剩2个空瓶子。然后你让老板先借给你一瓶汽水,喝掉这瓶满的,喝完以后用3个空瓶子换一瓶满的还给老板。如果小张手上有n个空汽水瓶,最多可以换多少瓶汽水喝?
public static int solution(int number){
if(number==1){
return 0;
}
if(number == 2){
return 1;
}
if(number >= 3){
int a = number/3;
int b = number%3;
int sum = 0;
sum = sum + a + solution(a+b);
return sum;
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
int number = sc.nextInt();
if(number == 0){
break;
}else {
int result = solution(number);
System.out.println(result);
}
}
}
5.逆序对
https://www.nowcoder.com/questionTerminal/bb06495cc0154e90bbb18911fd581df6
有一组数,对于其中任意两个数组,若前面一个大于后面一个数字,则这两个数字组成一个逆序对。请设计一个高效的算法,计算给定数组中的逆序对个数。
给定一个int数组A和它的大小n,请返回A中的逆序对个数。保证n小于等于5000。
测试样例:
[1,2,3,4,5,6,7,0],8
返回:7
public static int count(int[] A, int n) {
int count = 0;
for(int i = 0;i<n-1;i++){
for(int j = i+1;j<n;j++){
if(A[i]>A[j]){
count++;
}
}
}
return count;
}