博客
关于我
LeetCode面试题08.05.递归乘法
阅读量:70 次
发布时间:2019-02-26

本文共 618 字,大约阅读时间需要 2 分钟。

题目

在这里插入图片描述

题目链接
思路分析:
乘法实质就是多个相同的数相加,例如:3x4 等价于 3+3+3+3(4个3相加)即x*y的话,就是y个x相加
函数代码如下:

int Mul(int x, int y) {   	int result = 0;	if (y > 1) {   		result = Mul(x, y-1)+ x ;	}	else {   		result = x;	}	return result;}

分析过程:

在这里插入图片描述

在此优化了一下,刚刚正整数的函数部分已经写好了,那么再考虑负整数的话,可将这个情况转成刚才的求正数的情况再来计算。因此,可以添加一个函数来对y的值进行讨论。

具体代码实现如下:

int Mulhelper(int x, int y) {   	int result = 0;	if (y > 1) {   		result = Mulhelper(x, y-1)+ x ;	}	else {   		result = x;	}	return result;}int Mul(int x, int y) {   	if (y == 0) {   		return 0;	}	if (y > 0) {   		return Mulhelper(x, y);	}	else {   		return -Mulhelper(x, -y);	}}

此处注意:y<0的情况,转换为正整数进行计算,所以返回值要加负号 “-”

转载地址:http://nsg.baihongyu.com/

你可能感兴趣的文章
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
node exporter完整版
查看>>
node HelloWorld入门篇
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node JS: < 二> Node JS例子解析
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node 裁切图片的方法
查看>>
Node+Express连接mysql实现增删改查
查看>>
node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
查看>>
Node-RED中Button按钮组件和TextInput文字输入组件的使用
查看>>
vue3+Ts 项目打包时报错 ‘reactive‘is declared but its value is never read.及解决方法
查看>>
Node-RED中Switch开关和Dropdown选择组件的使用
查看>>
Node-RED中使用html节点爬取HTML网页资料之爬取Node-RED的最新版本
查看>>
Node-RED中使用JSON数据建立web网站
查看>>
Node-RED中使用json节点解析JSON数据
查看>>
Node-RED中使用node-random节点来实现随机数在折线图中显示
查看>>
Node-RED中使用node-red-browser-utils节点实现选择Windows操作系统中的文件并实现图片预览
查看>>
Node-RED中使用node-red-contrib-image-output节点实现图片预览
查看>>
Node-RED中使用node-red-node-ui-iframe节点实现内嵌iframe访问其他网站的效果
查看>>
Node-RED中使用Notification元件显示警告讯息框(温度过高提示)
查看>>