9

Check If A Large Number Is Divisible By 3 Or Not

 3 years ago
source link: http://siongui.github.io/2018/04/26/check-if-a-large-number-is-divisible-by-3-or-not/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

I saw this exercise from GeeksforGeeks [1], and it is a good example for type casting/conversion between int and string in Go.

The question is: Given a number, check if it is divisible by 3 or not.

The answer is: If a number is divisible by 3 if the sum of its digits is divisible by 3. For example, 12345 is divisible by 3, because 1+2+3+4+5=15, and 15 is divisible by 3.

Since Go is strongly-typed, we assume the number can be passed as either int or string type.

Number as int

Run Code on Go Playground

import (
      "strconv"
)

func IsIntDivisibleBy3(n int) bool {
      digits := strconv.Itoa(n)
      sumOfDigits := 0
      for _, digit := range digits {
              d, _ := strconv.Atoi(string(digit))
              sumOfDigits += d
      }

      return (sumOfDigits % 3) == 0
}

Example:

import (
      "testing"
)

func TestIsIntDivisibleBy3(t *testing.T) {
      if IsIntDivisibleBy3(123456758933312) != false {
              t.Error(123456758933312)
      }
      if IsIntDivisibleBy3(769452) != true {
              t.Error(769452)
      }
}

Number as string

Run Code on Go Playground

import (
      "strconv"
)

func IsStrDivisibleBy3(n string) (bool, error) {
      sumOfDigits := 0
      for _, digit := range n {
              d, err := strconv.Atoi(string(digit))
              if err != nil {
                      return false, err
              }
              sumOfDigits += d
      }

      return (sumOfDigits % 3) == 0, nil
}

Example:

import (
      "testing"
)

func TestIsStrDivisibleBy3(t *testing.T) {
      result, err := IsStrDivisibleBy3("3635883959606670431112222")
      if err != nil {
              t.Error(err)
      }
      if result != true {
              t.Error("3635883959606670431112222")
      }

      result, err = IsStrDivisibleBy3("123456758933312")
      if err != nil {
              t.Error(err)
      }
      if result != false {
              t.Error("123456758933312")
      }

      result, err = IsStrDivisibleBy3("769452")
      if err != nil {
              t.Error(err)
      }
      if result != true {
              t.Error("769452")
      }
}

Tested on:


References:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK