zoukankan      html  css  js  c++  java
  • LeetCode Golang 7. 整数反转

    7. 整数反转

    给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

    Tips : 

    Math包给出的类型大小的边界:

    // Integer limit values.
    const (
    	MaxInt8   = 1<<7 - 1
    	MinInt8   = -1 << 7
    	MaxInt16  = 1<<15 - 1
    	MinInt16  = -1 << 15
    	MaxInt32  = 1<<31 - 1
    	MinInt32  = -1 << 31
    	MaxInt64  = 1<<63 - 1
    	MinInt64  = -1 << 63
    	MaxUint8  = 1<<8 - 1
    	MaxUint16 = 1<<16 - 1
    	MaxUint32 = 1<<32 - 1
    	MaxUint64 = 1<<64 - 1
    )
    

      

    思路: Itoa --> 字符串反转 --> Atoi --> 判断大小

    package main
    
    import (
    	"fmt"
    	"math"
    	"reflect"
    	"strconv"
    	"unsafe"
    )
    
    //给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
    
    // 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31,  2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
    
    func reverse(x int) int {
    
    	if x < 10 && x > -10 {
    		return x
    	}
    
    	flag := 1 // 正负标志位 1 表示为正, -1表示为负
    	rst := x
    
    	if x < 0 {
    		flag = -1
    		rst *= flag // 转换为正数方便操作
    	}
    
    	rstString := ""
    	tmpString := strconv.Itoa(rst)
    	for i:=len(tmpString)-1;i>=0;i--{
    		rstString += string(tmpString[i])
    	}
    	//fmt.Println(rstString)
    
    	rst,err := strconv.Atoi(rstString)
    	if err != nil || rst > math.MaxInt32{
    		//fmt.Println("Atoi Error : ",err)
    		return 0
    	}
    
    	return rst * flag
    }
    
    //-2147483648到2147483647
    // 9646324351
    
    func main() {
    	x := reverse(1534236469)
    	fmt.Println(x,reflect.TypeOf(x),unsafe.Sizeof(x))
    }
    

      

  • 相关阅读:
    codeforces 938 C. Constructing Tests
    codeforces 981 C.Useful Decomposition
    Wannafly 挑战赛16 A 取石子
    codeforces 873 D. Merge Sort(分治)
    lightoj 1158
    lightoj 1226
    lightoj 1382
    lightoj 1283
    hdu 5445 Food Problem (多重背包)
    light 1205
  • 原文地址:https://www.cnblogs.com/gettolive/p/10204820.html
Copyright © 2011-2022 走看看