Table of Contents
回复内容:
Home Backend Development PHP Tutorial javascript - Looking for an algorithm? 0000000 sequence increment

javascript - Looking for an algorithm? 0000000 sequence increment

Aug 04, 2016 am 09:21 AM
c c++ java javascript php

举个栗子:0000000递增,格式是这样的:

<code>0000001
0000002
0000003
.....递增到10
0000010
.....递增到100
0000100
.....递增到100000
0100000
</code>
Copy after login
Copy after login

模仿着@G_Koala_C的回答,写了php版的:

<code>for ($i = 0; $i < 100; $i++) { 
    $zero = '';
    $k = 7-strlen($i);
    for ($j = $k; $j >0; $j--) { 
        $zero .= 0;
    }
    echo $zero.$i.'<br>';
}</code>
Copy after login
Copy after login

javascript - Looking for an algorithm? 0000000 sequence increment

回复内容:

举个栗子:0000000递增,格式是这样的:

<code>0000001
0000002
0000003
.....递增到10
0000010
.....递增到100
0000100
.....递增到100000
0100000
</code>
Copy after login
Copy after login

模仿着@G_Koala_C的回答,写了php版的:

<code>for ($i = 0; $i < 100; $i++) { 
    $zero = '';
    $k = 7-strlen($i);
    for ($j = $k; $j >0; $j--) { 
        $zero .= 0;
    }
    echo $zero.$i.'<br>';
}</code>
Copy after login
Copy after login

javascript - Looking for an algorithm? 0000000 sequence increment

js写法, 原理就是先算数字的长度,然后在前边补零。现在是到100,你可以把i改到100000

<code>for (var i = 0 ; i <= 100; i ++){
  var zero = "";
  for (var j = 7-i.toString().length; j > 0; j--) {
    zero += "0";
  }
  console.log(zero + i);
}</code>
Copy after login

其实是补零的问题额,Python 3写这样:

<code>["{:0>7}".format(i) for i in range(1, 100001)]</code>
Copy after login

再提供一个js的写法

<code>Array.from(Array(1000000).keys()).map(function(x){ return "0".repeat(8 - ("" + (x + 1)).length) + (x+1)})</code>
Copy after login

PHP

<code>for ($i=0;$i<=9999999;$i++) echo str_pad($i,7,"0",STR_PAD_LEFT);</code>
Copy after login

提供一个未来可能能使用的方法。。

<code>for (let i = 0; i <= 100; i++) console.log(String(i).padStart(7,'0'))</code>
Copy after login

<code>function incrace(){
    console.log((n=>(7-n.length)>0?(new Array(7-n.length+1)).join(0)+n:n)(String(i++)));
    setTimeout(incrace,500);
}
var i = 0;
incrace();
</code>
Copy after login

写完才发现问题已经解答了…js代码,供参考

JS

<code>var len = 10;    //长度
for (var i = 1; i <= 100; i++) {
    console.log((Array(len).join(0) + Math.abs(i)).slice(-len));
}</code>
Copy after login

来来来...上一套PHP版野路子

<code>// 定义一个位数比结果位数多的初始值
$base_num = 10000000;
// 开搞
for ($i = 0; $i < 100; $i++) {
    echo substr($base_num += $i, -7), "\n";
}</code>
Copy after login

看我C语言的:

<code>for (int i = 0; i < 10000000; i++) {
    printf("%07d\n", i);
}</code>
Copy after login

补零后的长度其实也是可配的:

<code>// 补零后长度, 注意printf的变化~
in len = 7;
for (int i = 0; i < 10000000; i++) {
    printf("%0*d\n", len, i);
}</code>
Copy after login

我发现很多回答都不是真正意义上的算法,我还以为类似C语言printf函数的实现呢.

上一个模拟printf函数的C语言实现吧,这个问题不用计算长度

请在支持C99的编译器上运行.(C89不支持)

<code>#include <string.h>
#include <stdlib.h>

void ltoa(long num, int width, char *str)
{
    static char digs[] = "0123456789";//为了方便扩展十六进制
    char ac[width+1];// C99支持; +1 是因为字符串必须以'\0'结尾,但这个不计入字符串长度.
    int i = width; // 这个变量可以直接用i代替的,但是这个函数是我之前写的,懒得改下面代码
    memset(&ac, '0', width); //直接把全部内存先置'0'
    ac[i] = '\0';//字符串结尾必须是'\0'
    
    //后面是整数转字符串的代码,思路就是除法和余数得到每一位数字(进制转换也是同样思想)
    //例如123 /10 = 12_3
    //   12 / 10 = 1_2
    //    1 / 10 = 0_1 
    //你可以看到,余数 3,2,1 倒置过来就是1,2,3.
    //把 3, 2 ,1 倒置复制到 内存空间就行了.
    if(num)
        ac[--i] = digs[num % 10];

    num = num / 10;
    while( 0 < num && 0 < i)
    {
        ldiv_t qr = ldiv(num, 10);
        // ldiv_t 用结构体,主要方便一次性取出余数和商
        num =  qr.quot;
        ac[--i] =  digs[qr.rem]; // 把0,1,3,4转换成'0','1','2','3',也可用0+'0' 的方法,但是上面已经说明,为了扩展到其他进制方便.
        
    }

    int n = sizeof(ac) - i;
    memcpy(str, &ac, width +1);//把字符串和\0 复制到缓冲区.
}
</code>
Copy after login

<code>    int max = 一个数字;
    for (int i = 0; i < max; i++) {
        String tem = "";
        for (int j = 0; j < len - (i + "").toString().length(); j++) {
            tem = tem + "0";
        }
        System.out.println(tem+i);
    }</code>
Copy after login

有人把值改成100000以上么

为啥没有C/C++版本啊。
看你们写的这么复杂我就放心了

这还要写什么算法吗?来个mysql版本的:

<code>CREATE TABLE `test` (
  `tid` int(7) UNSIGNED ZEROFILL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;</code>
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is the role of char in C strings What is the role of char in C strings Apr 03, 2025 pm 03:15 PM

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Apr 01, 2025 pm 03:06 PM

Causes and solutions for errors when using PECL to install extensions in Docker environment When using Docker environment, we often encounter some headaches...

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

Four ways to implement multithreading in C language Four ways to implement multithreading in C language Apr 03, 2025 pm 03:00 PM

Multithreading in the language can greatly improve program efficiency. There are four main ways to implement multithreading in C language: Create independent processes: Create multiple independently running processes, each process has its own memory space. Pseudo-multithreading: Create multiple execution streams in a process that share the same memory space and execute alternately. Multi-threaded library: Use multi-threaded libraries such as pthreads to create and manage threads, providing rich thread operation functions. Coroutine: A lightweight multi-threaded implementation that divides tasks into small subtasks and executes them in turn.

See all articles