1 func clumsy(N int) int {
 2     var ary []int
 3     for n := N; n >= 1; n-- {
 4         ary = append(ary, n)
 5     }
 6     re := N % 4 //4个数字一组
 7     firstgroup := true
 8     //最后一组如果不够4个,就补充到4个值,*和/补充1,+和-补充0,这样结果不变
 9     if re == 0 {
10         //不用补充
11     } else if re == 1 {
12         //补充3个
13         ary = append(ary, 1) //补充*1
14         ary = append(ary, 1) //补充/1
15         ary = append(ary, 0) //补充+0
16     } else if re == 2 {
17         ary = append(ary, 1) //补充/1
18         ary = append(ary, 0) //补充+0
19     } else if re == 3 {
20         ary = append(ary, 0) //补充+0
21     }
22     n := len(ary) //长度是4的倍数
23     var sum int
24     for a := 0; a <= n-4; a += 4 {
25         temp := ary[a] * ary[a+1] / ary[a+2]
26         if firstgroup { //第一组的G1*G2/G3是正
27             firstgroup = false
28         } else {
29             temp = temp * -1 //非第一组的G1*G2/G3是负
30         }
31         temp += ary[a+3]
32         sum += temp
33     }
34     return sum
35 }

这道题的思路就是把运算映射到数组的index上,形成一种规律的运算方式,在循环中进行处理。

posted on 2019-03-10 20:38  Sempron2800+  阅读(101)  评论(0编辑  收藏  举报