題意
將兩個最長為 104 的字串視為2進制數字相加,返回相加結果(以字串表示)。
注意
字串很長,超果基本型態所能儲存的最大值。
方法一 : toBigInteger(2) 、toString(2)
- toBigInteger(2) : 無法使用基本型態,所以需要將字串轉為 BigInteger 處理。因為要將字串視為 2 進制而非10進制,所以要傳入 2 。
- toString(2) : 要將兩數相加後獲得的 BigInteger 值用二進制顯示而非10進制,所以也要傳入2。因為要回傳的是 String 而非 BigInteger ,所以要轉為 String 。
class Solution { fun addBinary(a: String, b: String): String { return (a.toBigInteger(2) + b.toBigInteger(2)).toString(2) } }
163ms / 35.60MB (beats 80.11% / 64.99%)
0 comments:
張貼留言