Leetcode 441 Arranging Coins

Source: Internet
Author: User

Problem:

You had a total of n coins so want to form in a staircase shape, where every K-th Row must had E xactly k coins.

Given N, 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 = 5The coins can form the following rows:¤¤¤¤¤because the 3rd row is incomplete, we return 2.

Example 2:

n = 8The coins can form the following rows:¤¤¤¤¤¤¤¤because the 4th row is incomplete, we return 3.

Summary:

With n coins in a tower shape, the complete number of rows can be placed.

Analysis:

1. The simplest way of thinking, minus the increment of the number of coins per line, until n is a non-integer.

1 classSolution {2  Public:3     intArrangecoins (intN) {4         inti =0;5          while(N >0) {6i++;7N-=i;8         }9         Ten         returnn = =0? I:I-1; One     } A};

2. Solve the unary two-th equation: x^2 + x = 2 * N solution: x = sqrt (2 * n + 1/4)-1/2

But note that here n is a 32-bit signed integer number, 2 * n may overflow, so in the code should be handled accordingly.

1 class Solution {2public:3     int arrangecoins (int  n) {4         return sqrt (long long) 2 0.25 0.5 ; 5     }6 };

Leetcode 441 Arranging Coins

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.