Skip to content

Instantly share code, notes, and snippets.

@jikeytang
Last active August 29, 2015 14:01
Show Gist options
  • Save jikeytang/d1a71e69592ec582280f to your computer and use it in GitHub Desktop.
Save jikeytang/d1a71e69592ec582280f to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140521-题目1
今天三题由杭州-轨道提供,他的blog:http://blog.csdn.net/chriswenwu/
求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有用户控制。
回复时注意加上下面这句话,才会有语法高亮或格式缩进。
```javascript
@jiangtao
Copy link

jiangtao commented Jun 4, 2014

//借助repeat方法

function sum(num, n){

    var a = [], i = 0, res = 0;
    for(; i <= n; i++){
        res += ~~repeat(num, i);
    }
    return n ? res : 0;
}

function repeat(num, n){
    return new Array(n+1).join(num);
}

console.log(sum(2, 3));

@zhanhongtao
Copy link

加法: 从低位加到高位.

function sum( m, n ) {
  m = ~~m, n = ~~n;
  if ( m < 1 || n < 1 ) return m;
  var ret = m, cur = m, i = 0;
  while ( ++i < n ) {
    cur = cur * 10 + m;
    ret += cur;
  }
  return ret;
}

@wsgouwan
Copy link

    function getValue(v, num){     //   v代表数字, num代表几个
            if( num <= 1){
                return v ;
            }else{
                return v*fn( num ) + getValue(v, num - 1);
            }
        }

        function fn( num ){
                var a = '' ;
                for(var i = 0; i < num; i ++ ){
                    a += 1 ;
                }
                return parseInt(a); 
        };

        console.log( getValue( 3,3 ) )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment