面试题12:输入数字n,按照顺序打印出从1最大的n位十进制数。比如输入3,则打印出1、2、3一直到最大的3位数即999
2015-11-16 21:11
483 查看
// Print1ToMaxOfNDigits.cpp : Defines the entry point for the console application. // // 《剑指Offer——名企面试官精讲典型编程题》代码 // 著作权所有者:何海涛 #include "stdafx.h" #include <memory> void PrintNumber(char* number); bool Increment(char* number); void Print1ToMaxOfNDigitsRecursively(char* number, int length, int index); // ====================方法一==================== void Print1ToMaxOfNDigits_1(int n) { if(n <= 0) return; char *number = new char[n + 1]; memset(number, '0', n); number = '\0'; while(!Increment(number)) { PrintNumber(number); } delete []number; } // 字符串number表示一个数字,在 number上增加1 // 如果做加法溢出,则返回true;否则为false bool Increment(char* number) { bool isOverflow = false; int nTakeOver = 0; int nLength = strlen(number); for(int i = nLength - 1; i >= 0; i --) { int nSum = number[i] - '0' + nTakeOver; if(i == nLength - 1) nSum ++; if(nSum >= 10) { if(i == 0) isOverflow = true; else { nSum -= 10; nTakeOver = 1; number[i] = '0' + nSum; } } else { number[i] = '0' + nSum; break; } } return isOverflow; } // ====================方法二==================== void Print1ToMaxOfNDigits_2(int n) { if(n <= 0) return; char* number = new char[n + 1]; number = '\0'; for(int i = 0; i < 10; ++i) { number[0] = i + '0'; Print1ToMaxOfNDigitsRecursively(number, n, 0); } delete[] number; } void Print1ToMaxOfNDigitsRecursively(char* number, int length, int index) { if(index == length - 1) { PrintNumber(number); return; } for(int i = 0; i < 10; ++i) { number[index + 1] = i + '0'; Print1ToMaxOfNDigitsRecursively(number, length, index + 1); } } // ====================公共函数==================== // 字符串number表示一个数字,数字有若干个0开头 // 打印出这个数字,并忽略开头的0 void PrintNumber(char* number) { bool isBeginning0 = true; int nLength = strlen(number); for(int i = 0; i < nLength; ++ i) { if(isBeginning0 && number[i] != '0') isBeginning0 = false; if(!isBeginning0) { printf("%c", number[i]); } } printf("\t"); } // ====================测试代码==================== void Test(int n) { printf("Test for %d begins:\n", n); Print1ToMaxOfNDigits_1(n); Print1ToMaxOfNDigits_2(n); printf("Test for %d ends.\n", n); } int _tmain(int argc, _TCHAR* argv[]) { Test(1); Test(2); Test(3); Test(0); Test(-1); return 0; }
相关文章推荐
- 【黑马程序员】集合
- 西普ctf——《程序员的问题》
- 【黑马程序员】面向对象
- 【黑马程序员】方法与数组
- 来自苹果、谷歌、微软等知名公司六道有趣智力面试题
- 【黑马程序员】JAVA基础语法
- 【黑马程序员】JAVA基础知识概述
- “黑马程序员“OC学习初体验面向对象小例子
- 常见的面试C#技术题目
- 程序员
- PHP面试题
- php版 - 每个程序员1小时内必须解决的5个编程问题
- 北漂程序员的笑与泪
- 北漂程序员的笑与泪
- 干货来啦---国外程序员整理的java资源大全
- 程序员如何使用和提高搜索资料的技巧
- ssh框架面试总结
- 前端初级工程师面试题
- 为什么屌丝码农身边没有美女朋友
- 黑马程序员——分析匿名内部类使用外部定义的对象