Check if a number is divisible by 3

后端 未结 16 2929
予麋鹿
予麋鹿 2020-12-01 01:30

I need to find whether a number is divisible by 3 without using %, / or *. The hint given was to use atoi() function. Any

16条回答
  •  情书的邮戳
    2020-12-01 02:14

    The interview question essentially asks you to come up with (or have already known) the divisibility rule shorthand with 3 as the divisor.

    One of the divisibility rule for 3 is as follows:

    Take any number and add together each digit in the number. Then take that sum and determine if it is divisible by 3 (repeating the same procedure as necessary). If the final number is divisible by 3, then the original number is divisible by 3.

    Example:

    16,499,205,854,376
    => 1+6+4+9+9+2+0+5+8+5+4+3+7+6 sums to 69
    => 6 + 9 = 15 => 1 + 5 = 6, which is clearly divisible by 3.
    

    See also

    • Wikipedia/Divisibility rule - has many rules for many divisors

提交回复
热议问题