LeetCode算法题-Happy Number(Java实现)

Java算法实战:LeetCode跳跃问题与经典题解 本文还有配套的精品资源,点击获取 简介:LeetCode是一个面向开发者的在线编程挑战平台,特别适合准备技术面试的程序员。本项目专注于使用Java语言解决LeetCode上的经典算法题目,如“跳跃游戏”,“缺失的第一个正数”和“接雨水”。这些题目旨在提升开发者在数组处理、动态规划、贪心算法和逻辑思维方面的能力。项目包括对这些具体问题的详细解决方案,是提升Java编程应用能力... 阅读详情

这是悦乐书的第188次更新,第190篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第47题(顺位题号是202)。编写算法以确定数字是否“幸福”。

幸福数字是由以下过程定义的数字:从任何正整数开始,将数字替换为其数字的平方和,并重复该过程,直到最后数字等于1。这个过程以1结尾的那些数字是幸福的数字。如果陷入无限循环则不是幸福数字。例如:

输入:19
输出:true
说明:
1x1 + 9x9 = 82
8x8 + 2x2 = 68
6x6 + 8x8 = 100
1x1 + 0x0 + 0x0 = 1

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

从题目给的例子可以看出,每获得一个新的数字,都需要按照个十百位拆分然后计算乘积,直到最后得到的是1为止,而那些不是幸福数字的数,会陷入死循环里面,因此,我们需要将每次新计算得到的结果保存起来,如果下次计算的时候遇到,可以直接判断该数字不是幸福数字,因此我们使用HashMap来存值,使用递归来循环处理数据。因为需要多次使用Map,所以将其定义在方法外面,可以全局使用。

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
public boolean isHappy(int n) {
    if (n <= 0) {
    	return false;
    }
    if (n == 1) {
    	return true;
    }
    int index = 1;
    int sum = 0;
	for (int i=0; i <(n+"").length(); i++) {
    	sum += Math.pow((n+"").charAt(i)-'0', 2);
    }
	if (sum == 1) {
		return true;
	}
	if (map.containsKey(sum)) {
		return false;
	} else {
		map.put(sum, index++);
	}
    return isHappy(sum);
}

03 第二种解法

思路与上面一样,不过使用的是迭代的方法,所以,定义的HashMap放在你方法里面。使用了两层循环,外层控制map判断key是否存在以及替换新的n,内层循环处理新数不同位整数的平方和。

public boolean isHappy2(int n) {
    if (n <= 0) {
    	return false;
    }
    if (n == 1) {
    	return true;
    }
    Map<Integer, Integer> map2 = new HashMap<Integer, Integer>();
    int index = 1;
    int sum = 0;
	while (true) {
		for (int i=0; i <(n+"").length(); i++) {
        	sum += Math.pow((n+"").charAt(i)-'0', 2);
        }
    	if (sum == 1) {
    		return true;
    	}
    	if (map2.containsKey(sum)) {
    		return false;
    	} else {
    		map2.put(sum, index++);
    	}
    	n = sum;
    	sum = 0;
	}
}

04 第三种解法

如果你算过几个特殊的数,比如2、4、14、16、18,这些数字都会陷入死循环,并且是数字4.至于其他的数,如果不是幸福数,都会陷入死循环里面,死循环的入口就是4或者16,对此,我们可以不使用HashMap,只要判断新得到的数是否等于4或者16即可表示此数字不是幸福数字。

此解法同样是使用迭代的方法,借助两层循环,外层做判断,内层做不同位数字的平方和。

public boolean isHappy3(int n) {
	int sum = 0;
	while (sum != 1) {
		if (n == 4 || n == 16)
			break;
		while (n > 0) {
			int rem = n % 10;
			sum += rem * rem;
			n /= 10;
		}
		if (sum == 1)
			return true;
		n = sum;
		sum = 0;
	}
	return false;
}

05 第四种解法

使用HashSet,借助其不能存在重复元素的特性,思路和第一、第二种解法一样,都是先去获取新数的平方和,然后添加进HashSet,如果添加失败,说明已经存在该整数,即不是幸福数。不过这里是改变了n的原始值,所以最后判断的是n是否等于1。

public boolean isHappy4(int n) {
    HashSet<Integer> seen = new HashSet<>();
    while (seen.add(n)) {
        int square = 0;
        int sum = 0;
        while (n!=0) {
            square = n%10;
            sum += (square*square);
            n /=10;
        }
        n = sum;
    }
    return n==1 ? true : false;
}

06 第五种解法

借助环的思路。如果你还对之前的判断一个链表是否存在环的那道题目有印象的话,那么此题是与之类似的,每次新得到的数就代表一个节点,如果此节点出现过一次,即表示此链表是有环的,也就是说明此数是幸福数。

借助双指针,一个每次进行一次计算,另外一个每次计算两次,相当于速度是前一个的两倍,如果存在相同的数,两个指针肯定会相遇。

public boolean isHappy5(int n) {
    int slow = n;
    int fast = n;
    do {
        slow = digitSquareSum(slow);
        fast = digitSquareSum(fast);
        fast = digitSquareSum(fast);
        if (slow == 1 || fast == 1) {
        	return true;
        }
    } while(slow != fast);
    return false;
}

public int digitSquareSum(int n) {
    int sum = 0, tmp;
    while (n > 0) {
        tmp = n % 10;
        sum += tmp * tmp;
        n /= 10;
    }
    return sum;
}

07 小结

算法专题目前已连续日更超过一个月,算法题文章47+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

lrucacheleetcode-leetcode-collection:leetcode-collection lru缓存leetcode leetcode-collection 给定一个非空的整数数组,每个元素出现两次,除了一个。 找到那一个。 编写一个算法来确定数字n是否“快乐”。 快乐数是由以下过程定义的数字:从任何正整数开始,用其数字的平方和替换该数字,并重复该过程直到该数字等于 1(它将停留的位置),否则循环在一个不包括 1的循环中无限循环。这个过程以 1 结束的那些数字是快乐的数字。 如果n是一个快乐的数字,则返回 True,否则返回 False。 给定一个整数数组nums ,找到总和最大的连续子数组(至少包含一个数字)并返回其总和。 给定一个数组nums ,编写一个函数将所有0移动到它的末尾,同时保持非零元素的相对顺序。 假设您有一个prices数组,其中第 i 个元素是给定股票在第 i 天的价格。 设计一个算法来找到最大的利润。 您可以根据需要完成任意数量的交易(即多次买入和卖出一股股票)。 注意:您不得同时进行多项交易(即您必须先卖出股票,然后才能再次买入)。 给定一个字符串数组,将字谜组合在一起。 给定一个整数数组arr ,计算元素x使得x + 1也在arr 。 如果arr存 立即下载

相关推荐

leetcode202-leetcode202:202.快乐数写一个算法来判断一个数n是否快乐。快乐数字是由以下过程定义的数字:从任何正整数开

leetcode202 leetcode202 快乐数 编写一个算法来确定数字 n 是否快乐。 快乐数字是由以下过程定义的数字:从任何正整数开始,用其数字的平方和替换该数字。 重复这个过程,直到数字等于 1(它将停留在那里),或者它在一个不包括 1 的循环中无限循环。这个过程以 1 结束的那些数字是快乐的。 如果 n 是一个快乐的数字,则返回 true,否则返回 false。 跑步 Python解决方案.py Python版 Python 3.5 输入 现在可以在 n 变量中更改硬编码 leetcode 402测试用例在leet代码中通过

LeetCode常用算法整理

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 算法前言一、分治法可以解决的问题典型问题1. 归并排序2. 归并排序的衍生 前言 提示:可用于求解LeetCode的算法,在解题之前,先思考采用哪种算法合适。 提示:以下是本篇文章正文内容,下面案例可供参考 一、分治法 可以解决的问题 问题可以分解为若干个规模较小的相同问题,即该问题具有最优子结构性质; 利用该问题分解出的子问题的解可以合并为该问题的解; 该问题所分解出的各个子问题是相互独立的,即子问题之间不包含公共的子问题。 典型

weixin_43762968的博客 1188

leetcode 算法题 有答案java

目前 需要去面试 据说面试前需要做一道算法题 所以搜集了一些leetcode的算法题共享

LeetCode常用算法的总结

LeetCode经典算法的总结,带你走进算法的世界

huye930610的博客 2428

算法刷题LeetCode

算法刷题LeetCode 算法刷题LeetCode 算法刷题LeetCode

leetcode题库-learn-algorithm:常用/经典算法总结~

leetcode题库 算法学习笔记 本仓库内容 常用算法分析及源码 剑指 Offer 面试题及源码 牛客网刷题笔记 Something I hope you know before go into the coding~ First, please watch or star this repo, I'll be more happy if you follow me. Bug report, questions and discussion are welcome, you can post an issue or pull a request. 相关站点 GitHub地址: GitBook地址: LeetCode中国站: 南阳理工: ACM俱乐部: 目录 参考博客 郭耀华's Blog: 来自师范的学渣: 尘语凡心: Miracles happen every day: 参考书籍 总结 * 理解是第一要义~ * 写代码是一种艺术,而不是搬砖~ * 理论联系实际,知道怎么操作,代码要会写,源码要看的懂~ PS:仅为个人学习笔记总结,没有半毛钱商业利益。很多内容摘自网络,博主别打我。看

LeetCode 常用算法

LeetCode 常用算法1. 二分查找2. 广度优先搜索3. 深度优先搜索4. 排列5. 组合5. 链表5.1 反转链表5.2 链表两两交换元素5.3 链表检测成环5.4 查找链表的倒数第 K 个元素5.5 查找链表的中间元素5.6 查找链表成环位置的元素6. 排序6.1 Shell 希尔排序6.2 选择排序6.3 快速排序 1. 二分查找 def binary_search(data, target, left, right): while left <= right: m

David's Notes 1933

<硬件设计> 阻抗设计(二) 使用Si9000计算阻抗

阻抗设计(二) 使用Si9000计算阻抗

杰克拉力船长个人博客 1万+

常见算法总结【leetcode】

【注意:列出来的题目大部分是简单题;列出来的题目其最优解法不一定是本文中所说的算法,列举只是为了辅助更好的理解算法;

xiaod12138的博客 3875

支付宝支付(三):周期扣款实现注意细节

一、周期扣款实现说明 1、官方文档入口:https://opendocs.alipay.com/open/20190319114403226822/intro 2、根据官方文档说明,周期扣款有两种方式:先签约后代扣场景和支付后签约场景 3、周期扣款接入问题文档: a>https://opendocs.alipay.com/support/01rg24 b>https://opensupport.alipay.com/support/knowledge/50249/20160248753

新鲜雾霾的博客 5707

电机转矩、功率与转速:核心关系、公式推导与工程应用指南

在电气传动与自动化控制领域,理解旋转机械的核心物理量是进行设备选型、系统设计和故障诊断的基础。转矩、功率和转速构成了描述电机性能的“铁三角”,它们之间通过经典的物理公式紧密关联。从原理上讲,功率是单位时间内做功的能力,转矩是产生旋转运动的力矩,而转速则决定了运动快慢。这三者的关系(P = T × n / 9550)不仅是理论核心,更是工程实践中的关键计算工具,直接关系到电机的驱动能力、能耗与系统匹配。其技术价值在于,它为从微型伺服电机到大型工业传动系统的设计提供了统一的量化分析框架。在应用场景上,无论是为输

weixin_29184371的博客 264

happy number java_LeetCode算法题-Happy Number(Java实现)

这是悦乐书的第188次更新,第190篇原创01 看题和准备今天介绍的是LeetCode算法题中Easy级别的第47题(顺位题号是202)。编写算法以确定数字是否“幸福”。幸福数字是由以下过程定义的数字:从任何正整数开始,将数字替换为其数字的平方和,并重复该过程,直到最后数字等于1。这个过程以1结尾的那些数字是幸福的数字。如果陷入无限循环则不是幸福数字。例如:输入:19输出:true说明:1x1 +...

weixin_33520865的博客 292

git clone出现fatal: unable to access Failed to connect to github.com port 443: Timed out解决方案

本文主要介绍了git clone出现fatal: unable to access Failed to connect to github.com port 443: Timed out解决方案,希望能对使用git的同学们有所帮助。 文章目录 1. 问题描述 2. 解决方案

weixin_43178406的博客 23万+

【Leetcode】Happy Number

题目链接:https://leetcode.com/problems/happy-number/ 题目: Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any pos

业精于勤,荒于嬉 1867

KingSCADA实现按钮点击效果

哈喽,你好啊,我是雷工!在做SCADA项目的时候,按钮是不可缺少的功能,但软件自带的按钮太丑,已经无法满足现如今客户对界面美观度的要求。这时候就需要UI小姐姐设计美观大气的SCADA界面,但UI设计的按钮切图放到程序中只是图片素材,当添加了按钮功能时,虽然能实现按钮功能,但没有任何点击效果;当遇到有需要连锁条件才能点击的按钮时,操作员无法区分是有连锁点击了没反应,还是系统界面卡死了导致的没点击成功,这时候有点击效果就能很好的区分这种问题。本篇介绍一种实现按钮点击效果的方法,以下为操作过程。

做有价值的事,积累有价值的笔记! 2768

深度解读华为Limera:从舱内激光视觉融合看前融合技术的发展与演进

华为Limera激光雷达摄像头融合技术推动自动驾驶感知升级 华为推出的Limera创新性地将激光雷达与摄像头深度集成,采用共光路设计实现数据天然对齐,在小型障碍物识别等关键场景展现卓越性能。该产品代表了传感器前融合技术从分立走向共生的演进趋势,通过硬件级集成解决了多源异构数据融合难题。随着索尼堆叠式传感器等技术的出现,未来智能汽车感知系统将向高度集成的"超级传感器"方向发展,实现更精准的环境感知。Limera的发布标志着前融合技术从"可用"迈向"极致&quo

致力于lidar应用开发 401

【Leetcode】202-Happy Number【Java实现】【Easy】

Your runtime beats 82.86% of java submissions. stem: Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any pos

ALiTuTu的专栏 2285

设计四翼无人机(Quadcopter)的自主降落控制算法

为四翼无人机建立动力学模型,包括其姿态(Pitch, Roll, Yaw)和位置(X, Y, Z)的变化。可以使用Aerospace Blockset中的预制模块,或者根据具体需求构建自定义模型。示例:简化动力学模型利用块模拟四翼无人机的基本行为,确保模型能够反映电机输出如何影响姿态和位置变化。

amy_mhd的博客 244

LeetCode Happy Number

Write an algorithm to determine if a number is "happy".A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of

Coding for Dreams 2277

RK3588+YT9215快速拓展以太网口

YT9215支持7个端口的非阻塞数据传输,确保高效的数据流处理;在开发过程中,最重要的一点就是YT9215与RK3588的GMAC连接和配置部分,下面是gmac1对应dtsi文件的修改,包括注释掉rgmii_phy1对应的mdio1,以及gmac1对应的phy-handle部分,同时将gmac1修改成1000Mbps全双工模式。这就是最简单,最快速的RK3588拓展网口的方法了,如果需要用到交换芯片的其他功能,那就不可以直接使用原厂提供的bin,而是需要对YT9215进行另外的驱动开发。

带着耳朵取流浪的博客 2796

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

[LeetCode 202] Happy Number

题目链接:happy-number Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the numbe

瓦尔登湖 4160

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Leetcode_202_Happy Number

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.youkuaiyun.com/pistolove/article/details/45396585 Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace th

皮斯特劳沃 2370

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LeetCode 202:Happy Number

Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares

哈哈的个人专栏 2361

leetcode笔记:Happy Number

题目要求对任意一个正整数,不断各个数位上数字的平方和,若经过若干次运算后结果收敛到1,则该数字为Happy Number。

liyuefeilong的专栏 2229
上一篇: LeetCode算法题-House Robber(Java实现)
下一篇: LeetCode算法题-Remove Linked List Elements(Java实现)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值