zoukankan      html  css  js  c++  java
  • 剑指offer三十——整数中1出现的次数

    Markdown在线编辑器 - www.MdEditor.com

    欢迎使用 Markdown在线编辑器 MdEditor

    题目

    求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。

    解题思路

    核心想法:   求每个位上出现1的次数
    如求出现在十位上1的次数
    十位出现1的所有组合情况 共10个
    10
    11 只算十位出现的1 算1个
    ……
    19

    关键就是有多少种情况见下图



    代码

    int NumberOf1Between1AndN_Solution(int n)
    {
    int count = 0;
    int weight; // 个位对应1 十位对应2 百位对应3
    int max_weight = 0; // 最高位数
    //求最高位数
    int tmp = n;
    while (tmp != 0){
    max_weight++;
    tmp /= 10;
    }
    //依次不同位出现次数累加
    int front = 0, current =0,behind = 0;
    int uint = 1; // 第i位对应1后i-1个0
    for (int i = 1; i <= max_weight; i++) {
    uint = 1;
    for (int j = 1; j <= i - 1; j++) {
    uint *= 10;
    }
    front = n/(uint*10); // 去掉后i位
    current = (n / (uint)) % 10; //得到第i位
    behind = n % (uint); // 只剩后i-1位
    if(current == 0){
    count += front * uint;
    } else if(current == 1){
    count += front * uint + behind + 1;
    } else if (current > 1) {
    count += front * uint + uint;
    }
    }
    return count;
    }

    End

  • 相关阅读:
    [ssh] 通过ssh私钥生成公钥的方法
    [redis] hiredis-vip 简单使用
    [redis] redis cli的学习记录
    [ovs] 编写openflow流表的文档指引
    [iptables] 如何用iptables管理桥接模式下的设备
    [qemu][kvm] 在kvm嵌套kvm的虚拟机里启动kvm加速
    [qemu] 差分盘使用
    [yum] yum加速
    [ovs] openvswitch 从源码编译安装
    [qemu] qemu从源码编译安装
  • 原文地址:https://www.cnblogs.com/linxuesong/p/12201398.html
Copyright © 2011-2022 走看看