441. Arranging Coins(python+cpp)
阿新 • • 發佈:2018-12-19
題目:
You have a total of
n
coins that you want to form in a staircase shape, where everyk
-th row must have exactly k coins. Givenn
, find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. Example 1:n = 5 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ Because the 3rd row is incomplete, we return 2.
Example 2:
n = 8
The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ ¤ ¤ ¤
Because the 4th row is incomplete, we return 3.
解釋:
因為是連續求和,所以想到mid*(mid+1)/2
,然後可以通過二分查詢的方式找到mid。
python程式碼:
class Solution(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
if n <=0:
return 0
if n==1:
return 1
left=1
right=n
while left<=right:
mid=(left+right)/2
temp=(mid*(mid+1))/2
if temp==n:
return mid
elif temp>n:
right= mid-1
else:
left=mid+1
return left-1
c++程式碼:
class Solution {
public:
int arrangeCoins(int n) {
if (n<=0)
return 0;
int left=1,right=n;
while(left<=right)
{
long mid=left+(right-left)/2;
long tmp=mid*(mid+1)/2;
if(tmp==n)
return mid;
else if(tmp>n)
right=mid-1;
else
left=mid+1;
}
return left-1;
}
};
總結: c++用乘法的時候會超出範圍,所以注意要改變數值型別,注意,mid的資料型別一定要改成long,不然答案是錯的,可能是因為如果mid是int型別的,那麼它相乘的結果預設是用int儲存的,即使轉化為long型別,如果tmp過大,還是會變成負數,答案錯誤。