编程算法 - 从1到n整数中1出现的次数 代码(C)
来源:互联网 发布:海量数据去重 编辑:程序博客网 时间:2024/05/16 15:18
从1到n整数中1出现的次数 代码(C)
本文地址: http://blog.csdn.net/caroline_wendy
题目: 输入一个整数n, 求从1到n这n个整数的十进制表示中1出现的次数.
把拆分为最高位数字, 其余数字, 最后数字求解.
21345 -> 1346-21345[10000-19999, 最高位 + 1346-x1345其余位数] + 1-1345;
代码:
/* * main.cpp * * Created on: 2014年6月29日 * Author: wang */#include <stdio.h>#include <stdlib.h>#include <string.h>#include <limits.h>using namespace std;int PowerBase10(size_t n) {int result = 1;for (size_t i=0; i<n; ++i)result *= 10;return result;}int NumberOf1(const char* strN) {if (!strN || *strN<'0' || *strN>'9' || *strN == '\n')return 0;int first = *strN - '0';size_t length = strlen(strN);if (length == 1 && first == 0)return 0;if (length == 1 && first > 0)return 1;//最高位数字int numFirstDight = 0;if (first > 1)numFirstDight = PowerBase10(length-1);else if (first == 1)numFirstDight = atoi(strN+1) + 1; //+1去除最高位, 在加1//其余数字int numOtherDights = first*(length-1)*PowerBase10(length-2);//最后剩余int numRecursive = NumberOf1(strN + 1);return numFirstDight + numOtherDights + numRecursive;}int NumberOf1Between1AndN (int n) {if (n<=0)return 0;char strN[50];sprintf(strN, "%d", n);return NumberOf1(strN);}int main(void){ int result = NumberOf1Between1AndN(12); printf("result = %d\n", result); return 0;}
输出:
result = 5
4 0
- 编程算法 - 从1到n整数中1出现的次数 代码(C)
- 整数中1出现的次数(从1到n整数中1出现的次数)(算法)
- 整数中1出现的次数(从1到n整数中1出现的次数)
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- 从1到n整数中1出现的次数
- Visual Studio 2010 自定义精简安装
- 也谈面向对象
- learn with python-第十五章:对象的集合
- 黑马程序员_面向对象知识点整理
- IOS 序列化与反序列化 NSKeyedUnarchiver
- 编程算法 - 从1到n整数中1出现的次数 代码(C)
- java分页算法
- 选择合适的图表类型:折线图与面积图
- 2014年6月30日-7月6日(10小时,剩4414小时)
- cellForRowAtIndexPath 的标准用法
- Java生成文件夹
- ExtJS教程(7)---Ext.data.Store中事件的应用
- xode5
- 多线程之线程同步