Check if a number is divisible by 3

后端 未结 16 2823
予麋鹿
予麋鹿 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:10

    A number divisible by 3, iirc has a characteristic that the sum of its digit is divisible by 3. For example,

    12 -> 1 + 2 = 3
    144 -> 1 + 4 + 4 = 9
    
    0 讨论(0)
  • 2020-12-01 02:12
    • Here is a pseudo-algol i came up with .

    Let us follow binary progress of multiples of 3

    000 011
    000 110
    
    001 001
    001 100
    001 111
    
    010 010
    010 101
    
    
    011 000
    011 011
    011 110
    
    100 001
    100 100
    100 111
    
    101 010
    101 101
    

    just have a remark that, for a binary multiple of 3 x=abcdef in following couples abc=(000,011),(001,100),(010,101) cde doest change , hence, my proposed algorithm:

    divisible(x):
    
        y = x&7
    
        z = x>>3
    
        if number_of_bits(z)<4
    
            if z=000 or 011 or 110 , return (y==000 or 011 or 110) end
    
            if z=001 or 100 or 111 , return (y==001 or 100 or 111) end
    
            if z=010 or 101 , return (y==010 or 101) end
    
        end
    
        if divisible(z) , return (y==000 or 011 or 110) end
    
        if divisible(z-1) , return (y==001 or 100 or 111) end
    
        if divisible(z-2) , return (y==010 or 101) end
    
    end
    
    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-12-01 02:17

    well a number is divisible by 3 if all the sum of digits of the number are divisible by 3. so you could get each digit as a substring of the input number and then add them up. you then would repeat this process until there is only a single digit result.

    if this is 3, 6 or 9 the number is divisable by 3.

    0 讨论(0)
提交回复
热议问题