Go学习(1):基本语法简单应用

今天开始学Go了,技多不压身

基本语法大体来说感觉是:PythonJava的融合

具体的基本语法就不写了,大概写个简易的算法熟悉下这个语言

大数相加Go实现:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

/**
大数相乘
*/

func input() string {
    //输入
    reader := bufio.NewReader(os.Stdin)
    result, _, err := reader.ReadLine()
    if err != nil {
        fmt.Println("read from console err:", err)
        os.Exit(0)
    }
    return string(result)
}

func split(input string) (first string, second string) {
    //分割输入
    strSlice := strings.Split(input, "+")
    if len(strSlice) != 2 {
        fmt.Println("input error")
        os.Exit(0)
    } else {
        first = strings.TrimSpace(strSlice[0])
        second = strings.TrimSpace(strSlice[1])
        if first == "" || second == "" {
            fmt.Println("input error")
            os.Exit(0)
        }
    }
    return
}

func printResult(first, second, result string) {
    //打印结果
    fmt.Printf("%s + %s = %s\n", first, second, result)
}

func add(str1, str2 string) (result string) {
    //大数相加
    if len(str1) == 0 && len(str2) == 0 {
        result = "0"
    } else {
        //从个位开始
        index1 := len(str1) - 1
        index2 := len(str2) - 1
        //carry表示进位
        carry := 0
        //从各位开始依次相加
        for index1 >= 0 && index2 >= 0 {
            //ASCII码相减得出数值
            c1 := str1[index1] - '0'
            c2 := str2[index2] - '0'
            //模拟人算带进位相加
            sum := int(c1) + int(c2) + carry
            //进位处理
            if sum >= 10 {
                carry = 1
            } else {
                carry = 0
            }
            //得出项加后每一位的值
            c3 := (sum % 10) + '0'
            //拼接字符串
            result = fmt.Sprintf("%c%s", c3, result)
            index1--
            index2--
        }
        //第一个数的位数比第二个多的时候执行
        for index1 >= 0 {
            //原理和上面类似
            c1 := str1[index1] - '0'
            sum := int(c1) + carry
            if sum >= 10 {
                carry = 1
            } else {
                carry = 0
            }
            c3 := (sum % 10) + '0'
            result = fmt.Sprintf("%c%s", c3, result)
            index1--
        }
        //第二个数的位数比第一个多的时候执行
        for index2 >= 0 {
            c1 := str2[index2] - '0'
            sum := int(c1) + carry
            if sum >= 10 {
                carry = 1
            } else {
                carry = 0
            }
            c3 := (sum % 10) + '0'
            result = fmt.Sprintf("%c%s", c3, result)
            index2--
        }
        //处理最终进位
        if carry == 1 {
            result = fmt.Sprintf("1%s", result)
        }
    }
    return
}

func main() {
    //输入两个数
    first, second := split(input())
    //得到相加结果
    result := add(first, second)
    //打印
    printResult(first, second, result)
}

测试:

猜你喜欢

转载自www.cnblogs.com/xuyiqing/p/12435185.html