Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (caster )時間1年前 (2024/04/29 14:50), 編輯推噓2(206)
留言8則, 4人參與, 1年前最新討論串169/1548 (看更多)
※ 引述《Rushia (早瀬ユウカの体操服 )》之銘言: : https://leetcode.com/problems/minimum-number-of-operations-to-make-array-xor-equal-to-k/description : 2997. Minimum Number of Operations to Make Array XOR Equal to K : 給你一個陣列nums和一個數字k,我們希望將每個數字xor起來之後等於k,你可以使用一 : 個操作翻轉任意數字的任一位元,求出最少要翻幾次。 : 思路: : 1.假設 num1 ^ num2 ^ ... numn = x,我們希望 x == k 等價於 x ^ k == 0,所以我們 : 把 nums 的所有元素和 k 做 xor 然後看看翻轉幾個 1 可以令他為 0 即可。 : pycode : ------------------------------------------ : class Solution: : def minOperations(self, nums: List[int], k: int) -> int: : for num in nums: : k ^= num : return bin(k).count('1') : ------------------------------------------ 思路: 照抄大老思路 我原本還在一位一位比 母咪 Java Code: class Solution { public int minOperations(int[] nums, int k) { for (int i = 0;i<nums.length;i++){ k = k ^ nums[i]; } String bit_k=Integer.toBinaryString(k); int count = 0; for (int i = 0;i < bit_k.length();i++){ if(String.valueOf(bit_k.charAt(i)).equals("1")){ count++; } } return count; } } 有夠難寫 還是python寫起來比較爽 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.155.113 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1714373431.A.729.html

04/29 14:52, 1年前 , 1F
count = Integer.bitCount(k); 一步就好
04/29 14:52, 1F

04/29 14:53, 1年前 , 2F
大師
04/29 14:53, 2F

04/29 14:54, 1年前 , 3F
我記一下這函式 剛學java 現在只會基本操作
04/29 14:54, 3F

04/29 14:55, 1年前 , 4F
我想說找不到count 所以直接手搓一個
04/29 14:55, 4F

04/29 14:55, 1年前 , 5F
別卷了
04/29 14:55, 5F

04/29 14:57, 1年前 , 6F
速度100%了 感謝大老:))
04/29 14:57, 6F

04/29 14:58, 1年前 , 7F
Character也滿多靜態好用方法
04/29 14:58, 7F

04/29 15:01, 1年前 , 8F
好 我有空研究一下
04/29 15:01, 8F
文章代碼(AID): #1cBqCtSf (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cBqCtSf (Marginalman)