面试算法题1

来源:互联网 发布:java初学者看什么书比较好 编辑:程序博客网 时间:2024/04/29 21:09

/*
 * 有一个整数n,写一个函数f(n),返回0到n之间出现的"1"的个数。
 * 比如f(13)=6,现在f(1)=1,问下一个最大的f(n)=n的n是什么?
 * writed by chszs
 */

/**

 * @FileName: Test3.java
 * @Author
 * @Description:
 * @Date 2016年2月18日 下午3:59:15

 */
package com.cnp.andromeda.location.start;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


/**
 * @FileName: Test3.java
 * @author: ws
 * @Description:
 * @date: 2016年2月18日 下午3:59:15
 * @CopyRight :
 */
public class Test3{


    private static String  str      = null;
    private static Integer n        = 0;
    private static int     totalOne = 0;


    public static void main(String[] args) throws IOException{
        System.out.println("请输入一个整数:");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.valueOf(br.readLine());
        System.out.println("函数f(n)从0到n之间出现的'1'的个数为:" + Fn(n));
    }


    public static int Fn(Integer a){
        char[] re = a.toString().toCharArray();
        int le = re.length;
        int num = 0;
        int digit =getDigit(a);
        for(int i = le; i > 0; i--){
            if(re[le - i] == '1'){
                num = num + digit+1;
                num = num + (int)((i - 1) * (Math.pow(10, i - 2)));
            } else if(re[le - i] == '0'){
            } else{
                num = num + (int)(Integer.parseInt(re[le - i]+"") * (i - 1) * (Math.pow(10, i - 2)) + Math.pow(10, i - 1));
            }
            digit=getDigit(digit);
        }
        return num;
    }


    private static Integer getTopDigit(Integer a){
        String sTemp = String.valueOf(a);
        char ch = sTemp.charAt(0); // 返回第一个 也就是最高的数字
        return Integer.parseInt(ch + ""); // 就返回出来了
    }


    private static Integer getDigit(Integer a){
        String sTemp = String.valueOf(a);
        if(sTemp.length()==1){
            return 0;
        }
        String ch = sTemp.substring(1);
        return Integer.parseInt(ch + ""); // 就返回出来了
    }


}
0 0