名企编程题笔试

小米2017

 

1.树的高度

方法一:

var line;

var tree = [];

var n= read_line();

 

while(line = read_line()){

    var lines = line.trim().split(' ');

    tree[lines[1]]=lines[0] //tree[]=父;

}

 

var max=1;

for(var i=1;i<n;i++){

  var count =1;

  var item =tree[i];

  while(item){

       count++;

       if(count>max) max=count;

      item = tree[item];

  }

}

print(max)

方法二:

// Union Tree

 

var n = +read_line() ;

var tree = [undefined] ; // 0为根节点

for(var i=0; i< n-1; i++){

     line = read_line().split(/\s+/).map(function(it){return +it;})

    tree[line[1]] = line[0] ; // 每个位置保存当期索引值对应的父节点

}

 

var max  = 1;

 

for(var i = 1; i< n; i++){

 var count = 1;

 var item = tree[i] ;

 while(item != null){

   item = tree[item];

   count ++ ;

 }

  if(count > max) max = count;

}

 

print(max)

 

 

 

2。电话号码分身

方法一:

var l

while(l=read_line()){

  var n=+l

  while(n--){

    var t="",s=read_line()

    while(s.length>=1024) t+=s,s=read_line()

    t+=s

    var chars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

    for(var i=0;i<t.length;i++){

      chars[t.charCodeAt(i)-65]++

    }

    var all=calc(chars,t.length,[0,0,0,0,0,0,0,0,0,0]),rs=""

    for(var i=0;i<10;i++){

      rs+=Array(all[i]+1).join(i)

    }

   

    print(rs)

  }

}

function calc(c,s,r){

  //zero

  if(c[25]) {

    r[2]+=c[25] //10-8=2

    remove(c,"ZERO","Z")

  }

  //two

  if(c["W".charCodeAt()-65]) {

    r[4]+=c["W".charCodeAt()-65] //12-8=4

    remove(c,"TWO","W")

  }

  //four

  if(c["U".charCodeAt()-65]) {

    r[6]+=c["U".charCodeAt()-65] //14-8=6

    remove(c,"FOUR","U")

  }

  //five

  if(c["F".charCodeAt()-65]) {

    r[7]+=c["F".charCodeAt()-65] //15-8=7

    remove(c,"FIVE","F")

  }

  //six

  if(c["X".charCodeAt()-65]) {

    r[8]+=c["X".charCodeAt()-65] //16-8=8

    remove(c,"SIX","X")

  }

  //seven

  if(c["S".charCodeAt()-65]) {

    r[9]+=c["S".charCodeAt()-65] //17-8=9

    remove(c,"SEVEN","S")

  }

  //one

  if(c["O".charCodeAt()-65]) {

    r[3]+=c["O".charCodeAt()-65] //11-8=3

    remove(c,"ONE","O")

  }

  //eight

  if(c["G".charCodeAt()-65]) {

    r[0]+=c["G".charCodeAt()-65] //8-8=0

    remove(c,"EIGHT","G")

  }

  //nine

  if(c["I".charCodeAt()-65]) {

    r[1]+=c["I".charCodeAt()-65] //8-8=0

    remove(c,"NINE","I")

  }

  //three

  if(c["R".charCodeAt()-65]) {

    r[5]+=c["R".charCodeAt()-65] //13-8=0

    remove(c,"THREE","R")

  }

 

  return r

}

const nn=["ZERO", "ONE", "TWO", "THREE", "FOUR",

"FIVE", "SIX", "SEVEN", "EIGHT", "NINE"]

function remove(a,s,c){

  var n=a[c.charCodeAt()-65]

  for(var i=0;i<s.length;i++) a[s[i].charCodeAt()-65]-=n

}

 

 

3。句子反转

 

 

 

方法一:

var sc = read_line();

var arr = sc.split(' ');

var arr1 = arr.reverse();

var sc = arr1.join(' ');

print(sc)

 

方法二:

var line =read_line();

var index = -1;

var arr=[];

for(var i=0;i<line.length;i++){

     if(line.charAt(i)==" "){

      var str = line.substring(index+1,i);

      arr.push(str);

        //arr.push(line.substring(index+1,i));

        index = i ;

    }else if(i==line.length-1){

        var str = line.substring(index+1,i+1);

        arr.push(str);

    }

}

 

var res = arr.reverse().join(' ');

print(res);

 

方法三:

 

var data = read_line();

//print(data);

var arr = data.split(' ');

//print(arr);

arr = arr.reverse();

var result = arr.join(' ');

print(result);

 

 

方法四:

while(line=read_line()){

  var arr=line.split(" ");

  var result=arr.reverse();

  print(result.join(" "));

}

 

 

方法五:

var str = gets(10000);

str = str.split(' ').reverse().join(' ');

printsth(str);

 

方法六:

 

var originStr = '',

       res = '',

       tempArr = [];

 

while(originStr = read_line()) {

     tempArr = originStr.split(' ');

    res = tempArr.reverse().join(' ');

    print(res);

}

 

方法七:

function reverseString(str){

  var line = str.split(" ");

  var s = "";

  for (var key in line) {

    s = line[key] + " " + s;

  }

  return s.substring(0);

}

var str=read_line();

print(reverseString(str));

 

 

方法八:

function reverseString(str){

  var arr=str.split(' ');

  arr.reverse();

  var result=arr.join(' ');

  return result;

}

 

var str=read_line();

print(reverseString(str));

 

方法九:

var arr= read_line().split(" ");

var arr1=arr.reverse();

var str ="";

for(var i=0;i<arr1.length;i++){

str=str+arr[i]+" ";

}

print(str)

 

 

 

方法十:

 

var line;

while (line = read_line()) {

  words = line.split(" ");

  var s = "";

  for (var key in words) {

    s = words[key] + " " + s;

  }

  print(s.substr(0, s.length - 1));

}

 

 

 

 

方法十一:

var arr= read_line().split(" ");

var arr1=arr.reverse();

var str ="";

for(var i=0;i<arr1.length;i++){

str=str+arr[i]+" ";

}

print(str);

 

 

方法十二:

var line;

while(line = read_line()){

     line = line.split(' ');

   var j = line.length;

     for(var i=0;i<j;i++){

          print(line[line.length-i-1])

    }

}

 

方法十三:

var line;

while(line = read_line()){

  var arr = line.split(" ").reverse();

  print(arr.join(" "));

}

 

方法十四:

var line;

var data=[];

while( line = read_line() ){

   data.push(line.trim());

}

for(var i=0;i<data.length;i++){

 

   print( (data[i].split(' ').reverse().toString()).replace(/\,/g,' ')); 

 

}

 

方法十五:

var line;

var lines=[];

 

 while(line=read_line()){

     lines.push(line);

 }

for(var i=0;i<lines.length;i++){

    var value='';

    var tmp=lines[i].split(' ').reverse();

    for(var j=0;j<tmp.length;j++){

        value+=' '+tmp[j];

    }

    print(value)

}

 

 

方法十六:

var line;

 

while(line = read_line()) {

    print(reverse(line));

}

 

function reverse(str) {

    var arr1 = str.split(' ');

    arr1.map(function(s) {

        return s.split('').reverse().join('');

    })

    return arr1.reverse().join(' ');

}

 

 

 

 

百度2016实习生真题

 

 

 

1.乘法表

 

方法1:

var arr = read_line().split(' ');

var n = parseInt(arr[0]);

var m = parseInt(arr[1]);

var k = parseInt(arr[2]);

var left = 0, right = m * n, mid;

var sum;

 

while(left <= right){

  sum = 0;

  mid = Math.floor((left + right) / 2);

  for(var i = 1; i <= m; i++){

    sum += mid >= n * i ? n : Math.floor(mid / i);

  }

  if(sum < k){

    left = mid + 1;

  } else {

    right = mid - 1;

  }

}

print(left);

 

 

方法2:

var [n,m,k]=read_line().split(" ").map(Number);

function getLessThan(num){

  num=Number(num);

  var min=Math.min(n,m);

  var max=Math.max(n,m);

  var result=0;

  for(var i=1;i<=min;i++){

    result+=Math.min(Math.floor(num/i),max);

  }

  return result;

}

var start=1;

var end=n*m;

var currentNum=(start+end)/2;

while(getLessThan(currentNum)<k || getLessThan(currentNum-1)>=k){

  if(getLessThan(currentNum)<k){

    start=currentNum;

    currentNum=(start+end)/2;

  }else{

    end=currentNum;

    currentNum=(start+end)/2;

  }

}

print(Math.floor(currentNum))

 

方法3:

var [n,m,k]=read_line().split(" ").map(Number);

function getLessThan(num){

  num=Number(num);

  var min=Math.min(n,m);

  var max=Math.max(n,m);

  var result=0;

  for(var i=1;i<=min;i++){

    result+=Math.min(Math.floor(num/i),max);

  }

  return result;

}

var start=1;

var end=n*m;

var currentNum=(start+end)/2;

while(getLessThan(currentNum)<k || getLessThan(currentNum-1)>=k){

  if(getLessThan(currentNum)<k){

    start=currentNum;

    currentNum=(start+end)/2;

  }else{

    end=currentNum;

    currentNum=(start+end)/2;

  }

}

print(Math.floor(currentNum))

 

方法4:

function outputK(n,m,k){

   var left=0;

   var right=n*m;

   var mid;

   var sum;

 

   while(left<=right){

    sum=0;

    mid=Math.floor((left+right)/2);

     //????mid???

    for(var i=1;i<=m;i++){

      sum += mid>=n*i ? n : Math.floor(mid/i);

    }

    if(sum<k){

      left=mid+1;

    }else{

      right=mid-1;

    }

  }

    return left;

}

  var lines=read_line().split(' ');

  var n=parseInt(lines[0]);

  var m=parseInt(lines[1]);

  var k=parseInt(lines[2]);

  var result=outputK(n,m,k);

  print(result);

 

 

方法5:

function chengfabiao(str){

    var arr = str.split(" ");

    var n = parseInt(arr[0]);

    var m = parseInt(arr[1]);

    var k = parseInt(arr[2]);

 

    var left = 1,

        right = n*m,

        mid,result;

    while(left <= right){

        mid =  Math.floor((left + right)/2);

        var sum = cal(n,m,mid);

        if(k > sum){

          left = mid + 1;

        

        }else{

               right = mid - 1;

        }

    }

    return left;

}

function cal(n,m,mid){

    var sum = 0;

    for(var i = 1; i <= n; i++){

        sum += (mid >= (m*i)) ? m : Math.floor(mid/i);

    }

    return sum;

}

var line;

while(line = read_line()){

    print(chengfabiao(line));

}

 

方法6:

var line=read_line().split(' ');

var n=parseInt(line[0]),

    m=parseInt(line[1]),

     k=parseInt(line[2]);

var low=0,high=n*m,mid;

while(high>=low){

  var sum=0;

     mid=Math.floor((low+high)/2);

  for(var i=1;i<=m;i++){

    sum+=mid>=i*n?n:Math.floor(mid/i)

  }

     if(k>sum)low=mid+1;

  else high=mid-1;

}

print(low)

 

 

2.编号转换

 

 

 

方法1:

 

var all = readInt();

var reg = /^([A-Z]+)(\d+)$/;

while(all--){

toggle(read_line());

}

 

function toggle(i){

     if(reg.test(i)){ // ????????BC23

      var res = i.match(reg);

      var col = 0;

      var eng = RegExp.$1; // 'BC'

      var num = RegExp.$2; //23

      var base = eng.length - 1 ;

     

      for(var i = 0; i < eng.length; i++){

      col += (eng.charCodeAt(i) - 64) * Math.pow(26,base--);

      }

      print('R'+num+'C'+col);

    }else{

        var _reg = /R(\d+)C(\d+)/;

        var res = i.match(_reg);

      var col = +res[2];

      var row = res[1];

        var shang;

        var colB26 = [];

        while((shang = col/26) > 1){

          var yu = col%26;

          if(yu === 0){

               yu = 26;

               shang--;

          }

            colB26.unshift(String.fromCharCode(yu+64));

            col = Math.floor(shang);

        }

      colB26.unshift(String.fromCharCode(col+64));

        col = colB26.join('');

        print(col + row);

    }

};

 

 

方法2:

function exchange(input){

     var reg1=/^R(\d+)C(\d+)$/,

          reg2=/^([A-Z]+)(\d+)$/,

          row,col,result,position,code;

    if (input.match(reg1)!=null&&input.match(reg1).length==3){

        position=input.match(reg1);

        row=position[1];

        col=position[2];

        code='';

        while (col>0){

            m = col % 26;

            if (m==0){

                m = 26;

            }

            code =   String.fromCharCode(64 + parseInt(m)) + code;

            col = ( col - m ) /26;

        }

        result=code+row.toString();

            print(result);

    }else if(input.match(reg2)!=null&&(input.match(reg2).length==3)){

        position=input.match(reg2);

        var len=position[1].length;

        row=position[2];

        col=0;

        for(i=0;i<len;i++){

          var tmp=position[1][len-i-1];

            col=col+(tmp.charCodeAt(0)-64)*Math.pow(26,i);

        }

       result='R'+row.toString()+'C'+col.toString();

      print(result);

    }else{

    }

}

var num;

num=read_line();

for (i=1;i<=num;i++){

     exchange(read_line());

}

 

方法3:

 

var n=parseInt(read_line());

var chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');

for(var d=0;d<n;d++){

  var str=read_line();

  var arr=[];

  var result='';

  if(arr=str.match(/^R(\d+)C(\d+)$/)){

    var x=+arr[2],ary=[];

    while(x>0){

      x-=1;

      ary.push(x%26);

      x=(x-x%26)/26;

    }

   

    for(var j=0;j<ary.length;j++){

      result=chars[ary[j]]+result;

    }

    result+=arr[1]

    print(result)

}

else{

    arr=str.match(/^([A-Z]+)(\d+)$/);

    result='R'+arr[2]+'C';

    var l=arr[1].length,k=0;

    for(var i=0;i<l;i++){

      k=k*26+arr[1].charCodeAt(i)-'A'.charCodeAt(0)+1

    }

    result+=k;

    print(result);

  }

}

 

方法4:

var arr = "0ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('');

function ab2rc(str){

  var col = str.match(/[a-z]+/i)[0].toUpperCase().split('');

  var rowNum = str.match(/\d+/)[0];

  var colNum = 0;

  for(var i = 0, len = col.length; i < len; i++){

    var one = col.pop();

    colNum += arr.indexOf(one) * Math.pow(26, i);

  }

  print("R" + rowNum + "C" + colNum);

}

function rc2ab(str){

  var rc = str.match(/\d+/g);

  var row = rc[0], col = parseInt(rc[1]);

  var idx, cur, temp = 0;

  var colStr = [];

  do{

    cur = col % 26;

    col = Math.floor(col / 26);

    colStr.unshift(cur);

  }while(col);

  for(var i = colStr.length - 1; i >= 0; i--){

    if(colStr[i] <= 0 && i > 0){

      colStr[i - 1]--;

      colStr[i] += 26;

    }

    if(colStr[i]){

        colStr[i] = arr[colStr[i]];

    }

  }

  colStr = colStr.filter(function(item){

    return item !== 0;

  });

  colStr = colStr.join('');

  print(colStr + row);

}

 

var num = read_line();

num = parseInt(num);

var reg = /\d+C/i;

while(num){

  var str = read_line().trim();

  if(reg.test(str)){

    rc2ab(str);

  } else {

    ab2rc(str);

  }

  num--;

}

 

3.XML文档

 

 

方法1:

function parseXML(xml) {

  xml = xml.replace(/<!--[\s\S]+-->/g, '');

  var regex = /<\/?(\w+)>/g;

  var elements = xml.match(regex);

  if (!elements) {

    return 'Invalid';

  }

  var nodes = elements.map(element => {

    var type = element[1] === '/' ? 'end' : 'start';

    var name = element.match(/\w+/)[0];

    return {

      type: type,

      name: name

    }

  });

  var stack = [];

  nodes.forEach(node => {

    var last = stack[stack.length - 1];

    if (node.type === 'end' && last.type === 'start' && node.name === last.name) {

      stack.pop();

    } else {

      stack.push(node);

    }

  });

  if (stack.length === 0) {

    return 'Valid';

  } else {

    return 'Invalid';

  }

}

var line, input = '';

while (line = read_line()) {

  input += line;

}

print(parseXML(input));

 

百度2017秋招真题

 

1.找子串

 

方法1:

var str = readLine();

var mark = {};

var prev = str.charAt(0);

var o = {};

o[prev] = 1;

for(var i = 1; i < str.length; i++){

  var char = str.charAt(i);

  if(char == prev){

    if(o[char]){

      o[char]++;

    }else{

      o[char] = 1;

    }

  }else{

    if(!mark[prev] || mark[prev] < o[prev]){

      mark[prev] = o[prev];

    }

    prev = char;

    o = {};

    o[char] = 1;

  }

}

if(!mark[prev] || mark[prev] < o[prev]){

  mark[prev] = o[prev];

}

var sum = 0;

for(x in mark){

  sum += mark[x];

}

print(sum);

 

function readLine() {

     var line = "";

     var next = read_line();

     while(next.length >= 1024) {

          line += next;

          next = read_line();

     }

     line += next;

     return line;

}

 

方法2:

var str = readLine();

  var start = 0,i = 1,length = str.length;

  var startValue = str.charAt(0)+"1";

  var tempObj = {

    length: 0

  };

  if(length){

    tempObj[str.charAt(0)+0] = 1;

    tempObj.length++;

  }

 

  for(;i<length;i++){

    var pre = str.charAt(i-1);

    var cur = str.charAt(i);

    if(!tempObj[cur+"0"]){

      tempObj[cur+"0"] = 1;

      tempObj.length++;

    }

    if(pre === cur){

      var oLen = i-start;

      var value = pre+oLen;

      if(!tempObj[value]){

        tempObj[value] = 1;

        tempObj.length++;

      }

    }else{

      start = i;

    }

  }

  print(tempObj.length);

 

 

function readLine() {

     var line = "";

     var next = read_line();

     while(next.length >= 1024) {

          line += next;

          next = read_line();

     }

     line += next;

     return line;

}

                                                                      

方法3:

function readLine() {
     var line = "";
     var next = read_line();
     while(next.length >= 1024) {
          line += next;
          next = read_line();
     }
     line += next;
     return line;
}
                                      var str=readLine()
            var con={};
            var temp=1;
            var arr=str.split("");
            for(var i=0;i<arr.length;i++){
                if(!con[arr[i]]){
                    con[arr[i]]=1;
                }else if(con[arr[i]]&&arr[i]==arr[i-1]){
                    temp++;
                    if(con[arr[i]]<temp){
                        con[arr[i]]++
                    }
                    if(con[arr[i]]!=con[arr[i+1]]){
                        temp=1;
                    }
                }else{
                            temp=1
                }
            }
            var num =0;
            for(attr in con){
                num+=con[attr]
            }
            print(num)

 

 

 

 

 

 

 

2.十字架

 

 

 

方法1:

String.prototype.repeat = function(num){

  var s = "";//????????ES6???

  while(num--){

    s += this;

  }

  return s;

}

var t = +read_line();

var i = 1;

while(t--){

  print("Case #"+ i +":");

  var num = +read_line();

  var str = main(num);

  str.split(",").forEach(function(item){

    print(item);

  })

  i++;

}

 

function main (num) {

  if(num == 1){

    return "o";

  }else{

    var str = "";

    var k = Math.pow(3, num - 2);

    var prev = main(num - 1).split(",");

    for(var i = 0; i < k; i++){

      str = str + " ".repeat(k) + prev[i] + " ".repeat(k) + ",";

    }

    for(var i = 0; i < Math.ceil(k / 2); i++){

      str = str + prev[i].repeat(3) + ",";

    }

    var a = str.slice(0, -1).split(",");

    str = a.concat(a.slice(0, -1).reverse()).join(",");

    return str;

  }

}

 

 

方法2:

function makeTwoArray(num) {

  if (num === 1) {

    return [[true]];

  } else {

    let result = [];

    for (let i = 0; i < Math.pow(3, num - 1); i++) {

      result[i] = [];

    }

    let lastArray = arguments.callee(num - 1);

    for (let i = 1; i <= lastArray.length; i++) {

      for (let j = 1; j <= lastArray[i - 1].length; j++) {

        let flag = lastArray[i - 1][j - 1];

        if (flag) {

          result[3 * i - 1 - 1][3 * j - 1 - 1] = true;

          result[3 * i - 1 - 1][3 * j - 1 - 2] = true;

          result[3 * i - 1 - 1][3 * j - 1] = true;

          result[3 * i - 1 - 2][3 * j - 1 - 1] = true;

          result[3 * i - 1][3 * j - 1 - 1] = true;

        }

      }

    }

    return result;

  }

}

 

function printCross(num) {

  const crossArray = makeTwoArray(num);

  for (let i = 0; i < crossArray.length; i++) {

    let tempOut = '';

    for (let j = 0; j < crossArray[i].length; j++) {

      if (crossArray[i][j]) {

        tempOut += 'o';

      } else {

        tempOut += ' ';

      }

    }

    print(tempOut);

  }

}

 

function doTest() {

  let result = [];

  let times = parseInt(read_line(), 10);

  for (let i = 0; i < times; i++) {

    result.push(parseInt(read_line(), 10));

  }

  result.forEach((demon, index) => {

    print('Case #' + (index + 1) + ':');

    printCross(demon);

  })

}

 

doTest();

 

方法3:

function printLing (n) {        

          if(n == 1){

               return "o";

          }

          else{

               var s = "";

               var a = printLing(n - 1).split(",");

               var len = Math.pow(3, n - 1) / 3;

               for (var i = 0; i < len; i++) {

                    s += " ".repeat(len) + a[i] + ",";

               }

               for(var i = 0; i < len; i++){

                    var temp = a[i].length < len ? a[i] + " ".repeat(len - a[i].length) : a[i];

                    s += temp + temp + a[i] + ",";

               }

               for (var i = 0; i < len; i++) {

                    s += " ".repeat(len) + a[i] + ",";

               }

               return s.slice(0, s.length - 1);

          }

     }

     String.prototype.repeat = function (num){

      var str = "";

        for(var i = 0; i < num; i ++){

          str += this;

        }

      return str;

    }

          var n = +read_line();

          for(var i = 0; i < n; i++){

              var num = +read_line();

          print("Case #"+ (i + 1) +":");

          var a = printLing(num).split(",");

               for(var j = 0; j < a.length; j++){

            print(a[j]);

            }

           }

         

 

方法4:

var t=readInt();

for(var i=0;i<t;i++){

  var n=readInt();

  print(`Case #${i+1 }:`)

  for(var row of getMatrix(n) ){

    print(row);

  }

}

function blankMatrix(length){

  return (" ".repeat(length)+",").repeat(length).split(",").slice(0,-1);

}

function mConcat(...matrices){

  var result=[];

  for(var i in matrices[0]){

    result.push([]);

    for(var m of matrices){

      result[i]=result[i]+m[i];

    }

  }

  return result;

}

function getMatrix(n){

  if(n==1){

    return ["o"];

  }else{

    var result=[];

    var blank=blankMatrix(3**(n-2));

    var subMat=getMatrix(n-1);

    return [...mConcat(blank,subMat,blank),...mConcat(subMat,subMat,subMat),...mConcat(blank,subMat,blank)]

  }

}

 

 

3.排座位

 

方法1:

var t=read_line();

for(var i=0;i<t;i++){

var line=read_line().split(' ');

  var n=parseInt(line[0]);

  var m=parseInt(line[1]);

  if(m>(n/2))

    print(0);

  else{

  var sum=n;

    for(var j=m+1;j<=2*m-1;j++){

    sum=sum*(n-j)%1000000007;

    }

    print(sum);

  }

}

 

 

4.分数序列和

 

方法1:

var line;

var datas = [];

while(line = read_line()){

    line = line.split('\n');  // ????

    datas.push(line);

}

datas.shift();

while (datas.length) {

  var n = datas[0];

  var f1 = 2;

  var n1 = 1;

  var tmp = n1;

 

  var res = 0;

  var current = 0;

  for (var i = 0; i < n; i++) {

      current = f1 / n1;

      res += current

      n1 = f1;

      f1 = f1  + tmp;

      tmp = n1;

  }

  print(res.toFixed(4));

  //

  datas.shift(datas[0]);  // ????????? ???????

}

 

 

方法2:

var n = +read_line();

while(n--){

  var num = read_line();

  if(num == 1){

    print("2.0000");

  }else{

    var a = 2;

    var sum = a;

    for(var i = 2; i <= num; i++){

      a = 1 + 1 / a;

      sum += a;

    }

      print(sum.toFixed(4));

  }

}

 

方法3:


var line='';

 

line = read_line();

var count = parseInt(line);

var resArr = [];

 

function addon(cnt)

{

    var res = 0;

    var prev = 1;

    var prevp = 2;

    for(var i=1;i<=cnt;i++)

    {

       if(i==1){

         res+=2;    

        }else if(i==2){

         res+=1.5;    

        }else{

         res+= (prevp+prev+prevp) / (prev+prevp);  

            var tmp = prev;

            prev = prevp;

            prevp = tmp+prevp;

        }

    }

    return res.toFixed(4);

}

 

for(var i=0;i<count;i++)

{

    line = read_line();

    resArr.push(addon(parseInt(line)));

}

 

for(var i=0;i<resArr.length;i++)

{

    print(resArr[i]);    

}

 

方法4:

var fib = (function(n){

  var cache = {1:1, 2:2};

  return function baseFib(n) {

    if (!(n in cache)) {

        cache[n] = baseFib(n - 1) + baseFib(n - 2);

    }

    return cache[n];

  }

})();

 

var calc = function(n) {

 var sum = 0;   

  for (var i = 1; i <= n; i++) {

      sum += fib(i + 1) / fib(i);

    }

  return sum;

}

 

var line = read_line();

while(line = read_line()) {

     print(calc(line).toFixed(4));

}

 

方法5:

var line='';

line = read_line();

var count = parseInt(line);//????

var resArr = [];

 

function addon(cnt)

{

    var res = 0;

    var prev = 1;

    var prevp = 2;

  for(var i=1;i<=cnt;i++)

    {

      if(i==1){

          res+=2;    

        }else{

            var tmp = prev;

            prev = prevp;

            prevp = tmp+prevp;

            res+= (prevp / prev); 

        }

    }

    return res.toFixed(4);

}

 

for(var i=0;i<count;i++)

{

  line = read_line();//??????

    resArr.push(addon(parseInt(line)));

    print(resArr[i]);

 

}

 

方法6:

var line;

var lines= [];

var num =  read_line();//num组数据

for(var i=0;i < num ; i++){

       var n= read_line();

       lines.push(n);

}

//for(var i=1;i < 10 ; i++){

//  print(fb(i))

//}

 

function fb(n)

    var res = [1,2]; 

    if(n == 1 ){ 

        return 1

    }       

    for(var i=2;i<n;i++){ 

        res[i] = res[i-1] + res[i-2]; 

    } 

    return res[n-1]; 

 

 

 

var ans = 2;

for( var i = 0 ; i < lines.length ; i++){

       var numberN = parseInt(lines[i]);

 

          while( numberN > 1 ){

               ans =(  fb(numberN+1)/fb(numberN)   ) +ans;

               //print("@@"+"    "+fb(numberN+1) +"    "+fb(numberN)+"@@");

               numberN--;

       }

       print(ans.toFixed(4));

      ans =2;

}

//print(lines.length)

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值