[Leetcode] Self Dividing Numbers 自除数

ethannnli · · 517 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

Self Dividing Numbers

A self-dividing number is a number that is divisible by every digit it
contains.

For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.

Also, a self-dividing number is not allowed to contain the digit zero.

Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.

Example 1: Input: left = 1, right = 22

Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]

Note:
The boundaries of each input argument are 1 <= left <= right <= 10000.

暴力法

复杂度

时间 O(NM)

思路

从左到右,对每个数字依次取出其各个位的数字,然后判断是否能整除。

代码

func selfDividingNumbers(left int, right int) []int {
    var res []int
    for ; left <= right; left++ {
        curr := left
        for curr > 0 {
            rem := curr % 10
            // the digit can't be zero and should be divisible
            if rem == 0 || left%rem != 0 {
                break
            }
            curr = curr / 10
        }
        if curr == 0 {
            res = append(res, left)
        }
    }
    return res
}

有疑问加站长微信联系(非本文作者)

本文来自:Segmentfault

感谢作者:ethannnli

查看原文:[Leetcode] Self Dividing Numbers 自除数

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

517 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传