首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

大神,算法有关问题

2012-03-15 
大神求助,算法问题找出1到某个数的含有1这个数的个数,例如18,含有1的就是1,11,12,13,14,15,16,17,18[解决

大神求助,算法问题
找出1到某个数的含有1这个数的个数,例如18,含有1的就是 1,11,12,13,14,15,16,17,18

[解决办法]

Java code
class Main {    public static void main(String[] args) {        show(18);    }    private static void show(int n) {        String tmp = "";        for (int i = 1; i <= n; i++) {            // int 转 string            tmp = String.valueOf(i);            // 打印包含1的整数            if (tmp.contains("1")) {                System.out.print(i + ", ");            }        }    }}
[解决办法]
contains()
最终最终依靠的是这个函数
Java code
    static int indexOf(char[] source, int sourceOffset, int sourceCount,                       char[] target, int targetOffset, int targetCount,                       int fromIndex) {    if (fromIndex >= sourceCount) {            return (targetCount == 0 ? sourceCount : -1);    }        if (fromIndex < 0) {            fromIndex = 0;        }    if (targetCount == 0) {        return fromIndex;    }        char first  = target[targetOffset];        int max = sourceOffset + (sourceCount - targetCount);        for (int i = sourceOffset + fromIndex; i <= max; i++) {            /* Look for first character. */            if (source[i] != first) {                while (++i <= max && source[i] != first);            }            /* Found first character, now look at the rest of v2 */            if (i <= max) {                int j = i + 1;                int end = j + targetCount - 1;                for (int k = targetOffset + 1; j < end && source[j] ==                         target[k]; j++, k++);                if (j == end) {                    /* Found whole string. */                    return i - sourceOffset;                }            }        }        return -1;    } 

热点排行