Why computer professionals like to count starting from 0

Source: Internet
Author: User

Consider how you want to represent 2, 3, 4, 5, 6 these numbers now, and you have several representations:

    1. [2, 7)
    2. (1, 6]
    3. [2, 6]
    4. (1, 7)

Which Way is better? Let's consider the marginal condition:

When the left boundary is the smallest nonnegative integer (0), the left opening interval needs to indicate a negative number, ugly! The left-closed interval can be directly represented as a nonnegative integer, so that the left-most-bounded 左闭区间 representation wins. Exclude 2 and 4.

1 and 3 which is better? Let's consider the next extreme situation. When there is only one number, which is required to represent 2 the number range, the right-closed interval is represented as [2, 2], and the ugly! right-opening interval is expressed as [2, 3]. The right opening interval means winning. Exclude 3.

So, we choose the 1th representation method, that is, 左闭右开 the representation method.

In computer programming, it is often necessary to indicate the array subscript, the first position in the end from 0 good, or starting from 1 good?

左闭右开How to use the representation:

    • If the count is starting from 1, it is expressed as [1, n+1]
    • If the count is starting from 0, it is represented as [0, N)

Obviously, when counting from 0, it is more beautiful and practical, and the right digit subtracts the left number directly, that is, the number of the whole interval.

Why computer professionals like to count starting from 0

Related Article

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.