有A,B兩個同學想要分蘋果。A的想法是使用二進制進行,1 + 1相加不進一位,如(9 + 5 = 1001 +101 = 12)。B同學的想法是使用十進制進行,并且進一位。會輸入兩組數據,一組是蘋果總數,一組分別是每個蘋果的重量。如果讓B同學在滿足A同學的情況下獲取到蘋果的總重量且返回,如果不能則返回-1。
輸入
3
3 5 6
返回
11
備注:按照A同學的想法 5 + 6 =? 3 (101 + 110 = 010)文章來源:http://www.zghlxwxcb.cn/news/detail-606242.html
思路:異或運算,排序取最大文章來源地址http://www.zghlxwxcb.cn/news/detail-606242.html
/**
常用的位運算符:
與(&) 同1出1,有0出0
或(|)有1出1,全0出0
異或(^)相同出0,不同出1
非(~)又叫取反
左移 << (即乘2,最右邊加個0)
右移 >> (即除2刪掉最右邊一位)
*/
public class ShareApple {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = Integer.parseInt(sc.nextLine());
int[] apple = new int[num];
for (int i = 0; i < num ;i++){
apple[i] = sc.nextInt();
}
int x = 0;
for (int j = 0; j < apple.length;j++){
//把所有蘋果重量累加異或,如果結果為0則滿足A條件,那么B在所有蘋果中最小的一個給A,其它歸B
x ^= apple[j];
}
//能滿足A條件評分
if (x==0){
Arrays.sort(apple);
int bApple = 0;
for (int i = 1;i <apple.length;i++){
bApple +=apple[i];
}
System.out.println(bApple);
//不能滿足A條件分蘋果
}else if (x!=0){
System.out.println(-1);
}
}
}
到了這里,關于華為OD真題--分蘋果-帶答案的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!