作者Che31128 (飛天浣熊)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Wed Jun 7 09:39:49 2023
https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/
description/
1318. Minimum Flips to Make a OR b Equal to c
題目敘述:給三個正整數a,b,c,回傳(a || b)==c的最小翻轉數。
翻轉可將任意位置二元值的0,1調換。
Example 1:
https://assets.leetcode.com/uploads/2020/01/06/sample_3_1676.png
Input: a = 2, b = 6, c = 5
Output: 3
Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)
Example 2:
Input: a = 4, b = 2, c = 7
Output: 1
Example 3:
Input: a = 1, b = 2, c = 3
Output: 0
解題思路:
將c數與1做and,取出最右邊的數是否為0,
如果是0判斷a,b是否為1,是的話進行反轉,
如不是0判斷同樣判斷a,b,同時為0時反轉一次。
java code
--------------------------------------------------------------------------
class Solution {
public int minFlips(int a, int b, int c) {
int ans=0;
while(a>0 || b>0 || c>0){
if((c&1)==0)
ans += (a & 1) + (b & 1);
else
if((a & 1) == 0 && (b & 1)==0)
ans++;
a >>= 1;
b >>= 1;
c >>= 1;
}
return ans;
}
}
--------------------------------------------------------------------------
姆咪
--
https://i.imgur.com/P91SrVW.jpg
https://i.imgur.com/f3LWwYN.jpg
https://i.imgur.com/ZWq4cAe.jpg
https://i.imgur.com/QCF3fwE.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.141.107 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1686101998.A.419.html
推 DreaMaker167: 你板剩我連easy都不會了 06/07 09:40
→ Rushia: 大師 06/07 14:06
推 NTHUlagka: 東窩率 持之以恆 leetcoder變googler 06/07 21:53