441_ Arranging_Coins

旧城等待, 2022-06-08 00:51 269阅读 0赞
  1. /*
  2. 441. Arranging Coins
  3. You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
  4. Given n, find the total number of full staircase rows that can be formed.
  5. n is a non-negative integer and fits within the range of a 32-bit signed integer.
  6. Example 1:
  7. n = 5
  8. The coins can form the following rows:
  9. ¤
  10. ¤ ¤
  11. ¤ ¤
  12. Because the 3rd row is incomplete, we return 2.
  13. */
  14. //思路,就像高斯定理一样,首项加末项乘香树除以2就是n
  15. //解法一 83% 23ms
  16. int arrangeCoins(int n) {
  17. long long int i = n;
  18. i = (sqrt(8*i+1)-1)/2;
  19. return i;
  20. }
  21. /解法二 98% 19ms
  22. //我试着把long long int 改成float,但是2146467959数据没法通过, 超出了范围,如果改成double就可以了。直接怼到98.65%
  23. int arrangeCoins(int n) {
  24. double i = n;
  25. i = (sqrt(8*i+1)-1)*0.5;
  26. return i;
  27. }

发表评论

表情:
评论列表 (有 0 条评论,269人围观)

还没有评论,来说两句吧...

相关阅读