• 数组:整数中1出现的次数(从1到n整数中1出现的次数)


    题目描述

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

    解题思路

    三种解法:

    法一:依次遍历每个数,判断每个数里面是否包含1;

    法二:同法一,将数字转成字符串,直接判断;

    参考代码

    法1:运行时间:17ms  占用内存:9300k

     1 public class Solution {
     2     public int NumberOf1Between1AndN_Solution(int n) {
     3         int res = 0;
     4         for(int i = 0; i <= n; i++) {
     5             res += number1(i);
     6         }
     7         return res;
     8     }
     9     
    10     private int number1(int n) {
    11         int res = 0;
    12         while(n > 0) {
    13             if(n % 10 == 1) {
    14                 res++;
    15             }
    16             n = n / 10;
    17         }
    18         return res;
    19     }
    20 }
    View Code

    法2:运行时间:45ms  占用内存:11664k

     1 public class Solution {
     2     public int NumberOf1Between1AndN_Solution(int n) {
     3         int res = 0;
     4         StringBuffer s = new StringBuffer();
     5         for(int i = 0; i <= n; i++) {
     6             s.append(i);
     7         }
     8         String str = s.toString();
     9         for(int i = 0; i < str.length(); i++) {
    10             if(str.charAt(i) == '1') {
    11                 res++;
    12             }
    13         }
    14         return res;
    15     }
    16 }
    View Code
  • 相关阅读:
    格式化占位符%r和!r
    Counter函数
    java 字符串的比较
    Mac下aapt命令获取安卓app activity
    Mac + python + adb 实现安装apk包到安卓手机
    python下载apk包并将其保存到指定目录
    python+adb实现批量卸载安装apk文件
    python实现获取接口开始请求时间点
    adb: no devices/emulators found报错解决方案
    Windbg命令系列.printf
  • 原文地址:https://www.cnblogs.com/carry6/p/11519443.html
Copyright © 2020-2023  润新知