Leetcode #56 #338 #344 #292 #371 Solution

Try a blog in Markdown mode.

56 Merge Intervals

Solution:

  • O(nlogn) Sort all Intervals
  • O(n) Merge them

338 Counting Bits

Solution:

  • ‘10011’ in binary system means ‘2^0+2^1+2^4’ in decimal system.
  • We can get the number of 1 in ‘10011’ if we know it in ‘0011’, because it is the number of 1 in ‘0011’ plus 1.
  • Let f[n] be the number of 1 in number ‘n’. We have f[10011]=f[0011]+1
  • Set f[0]=0 first. How to get f[i]?
  • Suppose i=2^t+…, then f[i]=f[i-2^t]+1
  • For i=2^t, f[i]=1
  • Finish it. O(n) for this program

344 Reverse String

Solution:

  • O(n)Reverse String

292 Nim Game

Solution:

  • return N % 4;

371 Sum of Two Integers

Solution:

  • Bitwise operations.
  • How to calculate 10011+11010 ?
  • No carry propagation,1+1=0; 0+1=1; 0+0=0; Same rule as XOR operation .
  • 10011 XOR 11010=01001.
  • While in fact 1+1=10; 0+1=01; 0+0=00; for the 1 in high bit, we use AND operation.
  • 10011 AND 11010 =10010.
  • 10010 << 1=100100.
  • Now, if you could calculate 01001+100100 without using ‘+’, you could finish this question.
  • Ask me how? No reply.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值