华为专区:https://www.nowcoder.com/exam/oj/ta?tpId=37
华为OD模拟面试:
https://www.nowcoder.com/exam/test/87506907/submission?pid=1088888
1.汽水瓶
某商店规定:三个空汽水瓶可以换一瓶汽水,允许向老板借空汽水瓶(但是必须要归还)。
小张手上有
n
n 个空汽水瓶,她想知道自己最多可以喝到多少瓶汽水。
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();
if (a ==0 ) {
return;
}
int result = getNum(a,0);
System.out.println(result);
}
}
public static int getNum(int b,int c) {
if (b <= 1) {
return c;
}
if (b == 2) {
return c + 1;
}
return getNum(b-2,c+1);
}
}
2.明明的随机数
对于明明生成的 n 个 1 到 500 之间的随机整数,你需要帮助他完成以下任务:
∙ 删去重复的数字,即相同的数字只保留一个,把其余相同的数去掉;
∙ 然后再把这些数从小到大排序,按照排好的顺序输出。
你只需要输出最终的排序结果。
∙ 删去重复的数字,即相同的数字只保留一个,把其余相同的数去掉;
∙ 然后再把这些数从小到大排序,按照排好的顺序输出。
你只需要输出最终的排序结果。
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean first = true;
int num = 0;
int[] array = new int[num];
int index = 0;
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int a = in.nextInt();
if (first) {
num = a;
first = false;
array = new int[num];
} else {
array[index++] = a;
}
}
getValue(array);
}
public static void getValue(int[] a) {
for (int i = 0 ; i < a.length; i++) {
for (int j = 0 ; j < a.length - i - 1; j++) {
if ((a[j] ^ a[j + 1]) == 0) {
a[j] = 0;
}
if (a[j] > a[j + 1]) {
int tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
}
}
}
for (int i = 0 ; i < a.length; i++) {
if (a[i] == 0) {
continue;
}
System.out.println(a[i]);
}
}
}
3.进制转换
对于给定的十六进制数,输出其对应的十进制表示。
在本题中,十六进制数的格式为:0x 开头,后跟若干个十六进制数字( 0-9 和 A-F )。其中,A-F 依次代表 10−15 。
在本题中,十六进制数的格式为:0x 开头,后跟若干个十六进制数字( 0-9 和 A-F )。其中,A-F 依次代表 10−15 。
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
String a = in.next();
int len = a.length();
int result = 0;
for (int i = len - 1; i >= 2 ; i--) {
char c = a.charAt(i);
int v = getValue(c);
result += getNum(v,len - i);
}
System.out.println(result);
}
public static int getNum(int v,int i) {
int result = 1;
for (int j = 1 ; j < i ; j++) {
result *= 16;
}
return v * result;
}
public static int getValue(char c) {
if (c == 'A') {
return 10;
} else if (c == 'B') {
return 11;
} else if (c == 'C') {
return 12;
} else if (c == 'D') {
return 13;
} else if (c == 'E') {
return 14;
} else if (c == 'F') {
return 15;
} else {
return c - '0';
}
}
}