小言_互联网的博客

Go语言实现To square(root) or not to square(root)

284人阅读  评论(0)

描述

Write a method, that will get an integer array as parameter and will process every number from this array.
Return a new array with processing every number of the input-array like this:
If the number has an integer square root, take this, otherwise square the number.
[4,3,9,7,2,1] -> [2,9,3,49,4,1]
The input array will always contain only positive numbers and will never be empty or null.
The input array should not be modified!

分析

实现

import "math"

func SquareOrSquareRoot(arr []int) []int{
  var s []int // Note 1
  for _, v := range arr {
    t := math.Sqrt(float64(v)) // Note 2
    if t == math.Floor(t) {
      s = append(s, int(t)) // Note 3
    } else {
      s = append(s, v * v)
    }
  }
  return s
}

注1:已知目的slice长度,可以通过s := new([]int, len(arr))预先分配slice长度,提高性能。
注2:math.Sqrt参数为float64,如果输入为int,必须强制转换。
注3:整型转为浮点型:f := float64(i); 浮点型转为整型:i := int(f)


转载:https://blog.csdn.net/thinshootout/article/details/102219835
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场