找不到工作就写go题(整数的各位积和之差)

给你一个整数 n,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。

示例 1:

输入:n = 234
输出:15
解释:
各位数之积 = 2 * 3 * 4 = 24
各位数之和 = 2 + 3 + 4 = 9
结果 = 24 - 9 = 15
示例 2:

输入:n = 4421
输出:21
解释:
各位数之积 = 4 * 4 * 2 * 1 = 32
各位数之和 = 4 + 4 + 2 + 1 = 11
结果 = 32 - 11 = 21

func subtractProductAndSum(n int) int {
    if n>=1 && n<10{
        return 0
    }
    var sum, product, remainder, quote int
    product=1   //注意这里乘积初始化为1
    quote = n
    for{
        remainder = quote%10
        quote /=10
        product*=remainder
        sum+=remainder
        if quote == 0{
            break;
        }
    }
    return product-sum
}
发布了13 篇原创文章 · 获赞 0 · 访问量 151

猜你喜欢

转载自blog.csdn.net/JACK_GEN123/article/details/104414931