I am running into an issue, which seems to be related to int32 vs int data type. My program is returning different values on different environments.
For example, on go playground, I notice the value returned is -4 (which is expected value). But the same on Leetcode with same input returns a value of 4294967292. While it returned this value, when I print it, I get -4 ( see output added later).
I tried casting to int32(res) but didn't help. Also didn't find any directly related in textbook. Please help me understand why this is different on playground vs lc.
https://play.golang.org/p/qXMd9frlhbe
package main
import (
"fmt"
)
func main() {
fmt.Printf("%v", singleNumber([]int{-2,-2,1,1,-3,1,-3,-3,-4,-2}))
}
func singleNumber(nums []int) int {
sum := make([]int, 32)
for _, v := range nums {
for i := 0; i < 32; i++ {
if sum[i] != 0 {
sum[i] += 1 & (v >> uint32(i))
} else {
sum[i] = 1 & (v >> uint32(i))
}
}
}
res := 0
for k, v := range sum {
if (v%3) != 0 {
res |= (v%3) << uint32(k)
}
}
fmt.Printf("res %+v
", res)
return res
}
Same on Leetcode gives the output:-
Input:
[-2,-2,1,1,-3,1,-3,-3,-4,-2]
Output:
4294967292
Expected:
-4
Stdout:
res -4
The textbook you are looking for is
The Go Programming Language Specification
A numeric type represents sets of integer or floating-point values. The predeclared architecture-independent numeric types are:
uint32 set of all unsigned 32-bit integers (0 to 4294967295) uint64 set of all unsigned 64-bit integers (0 to 18446744073709551615) int32 set of all signed 32-bit integers (-2147483648 to 2147483647) int64 set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
There is also a set of predeclared numeric types with implementation-specific sizes:
uint either 32 or 64 bits int same size as uint
Check the size of type int
. On the Go Playground it's 4 bytes or 32 bits.
package main
import (
"fmt"
"runtime"
"unsafe"
)
func main() {
fmt.Println("arch", runtime.GOARCH)
fmt.Println("int", unsafe.Sizeof(int(0)))
}
Playground: https://play.golang.org/p/2A6ODvhb1Dx
Output (Playground):
arch amd64p32
int 4
Run the program in your (LeetCode) environment. It's likely 8 bytes or 64 bits.
For example, in my environment,
Output (Local):
arch amd64
int 8
Here are some fixes to your code,
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Println(runtime.GOARCH)
fmt.Printf("%v
", singleNumber([]int{-2, -2, 1, 1, -3, 1, -3, -3, -4, -2}))
}
func singleNumber(nums []int) int {
sum := make([]int, 64)
for _, v := range nums {
for i := range sum {
sum[i] += 1 & (v >> uint(i))
}
}
res := 0
for k, v := range sum {
if (v % 3) != 0 {
res |= (v % 3) << uint(k)
}
}
fmt.Printf("res %+v
", res)
return res
}
Playground: https://play.golang.org/p/kaoSuesu2Oj
Output (Playground):
amd64p32
res -4
-4
Output (Local):
amd64
res -4
-4