首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往
您找到你想要的搜索结果了吗?
是的
没有找到

LeetCode笔记:202. Happy Number

一看到这个题目我是懵逼的,看一个数字是不是happy,出题人真有童心。想找规律吧算了几个数字感觉没得规律找啊。从最简单的思路来看就是不断循环看最后得到的是不是1了,但是返回true的判断容易,什么时候就可以下结论说这个数字不happy呢?这才是问题。首先我们得到的数不知道是几位数,但是经过计算后最后肯定会变成个位数,而如果这个个位数是1那就是happy了,如果不是1应该就是不happy吧。所以我一开始的做法是循环求平方和,直到结果是个位数了就看是不是1来给出结果,这里还用到了一个递归,如果计算一次平方和还不是个位数就继续递归计算。 提交后发现有个错误,那就是1111111这个数,也是一个happy数字,但我判断为不是了。我数了一下一共七个1,平方和是7,才知道原来到了个位数后还会继续计算,我算了一下发现7还真能最后算出1来,那只能对于1~9九个个位数都看看是不是能算出1来了,算了一下觉得太麻烦了,于是想到了一个简单的方法,leetcode是可以自定义测试用例的,勾选Custom Testcase就可以了,然后我把4~9都试了一遍,不用试2、3是因为就等于4、9,测完发现只有1和7是的,所以在代码里把7也算成true就可以了。 最后的时间是4ms,还不错,看了看discuss也没有看到特别好的方法,那大抵就是这样了吧。

03

【HDU 4940】Destroy Transportation system(无源无汇带上下界可行流)

Tom is a commander, his task is destroying his enemy’s transportation system. Let’s represent his enemy’s transportation system as a simple directed graph G with n nodes and m edges. Each node is a city and each directed edge is a directed road. Each edge from node u to node v is associated with two values D and B, D is the cost to destroy/remove such edge, B is the cost to build an undirected edge between u and v. His enemy can deliver supplies from city u to city v if and only if there is a directed path from u to v. At first they can deliver supplies from any city to any other cities. So the graph is a strongly-connected graph. He will choose a non-empty proper subset of cities, let’s denote this set as S. Let’s denote the complement set of S as T. He will command his soldiers to destroy all the edges (u, v) that u belongs to set S and v belongs to set T.  To destroy an edge, he must pay the related cost D. The total cost he will pay is X. You can use this formula to calculate X:

01
领券