京东幸运数求解

用的最暴力的方法,想好久没想到快速解法。。
全部评论
不需要暴力求解,其实你可以把它想象成一个0 1字符串,然后就行求解即可。 public static void main(String args[]) { Scanner reader = new Scanner(System.in); while (reader.hasNextLine()) { int num = Integer.parseInt(reader.nextLine()); for (int i = 0; i < num; i++) { int count = Integer.parseInt(reader.nextLine()); if (count == 1) { System.out.println(4); continue; } if (count == 2) { System.out.println(7); continue; } int a = 1; while (Math.pow(2, a) - 2 < count) { a++; } count = (int) (count - Math.pow(2, a - 1) + 2); count--; StringBuilder sb = new StringBuilder(); for (int j = 0; j < a - 1; j++) { int index = 1 << j; if ((count & index) == 0) { sb.append("4"); } else { sb.append("7"); } } System.out.println(sb.reverse().toString()); } } }
点赞 回复 分享
发布于 2016-09-05 21:23
暴力过了80%,知道应该优化一下。现在一想,其实就是简单的求和超过了32(或者64?)就可以直接忽略该数不用算下去。
点赞 回复 分享
发布于 2016-09-05 21:25
我用java超时了,最后那个第1000000000,我程序用了4s跑出来
点赞 回复 分享
发布于 2016-09-05 21:21
#include <iostream> #include <string> #include <cmath> #include <vector> using namespace std; string getKthNum(long long k) {     if (k == 1) {         return "4";     } else if (k == 2) {         return "7";     }     int numPos = ceil(log(k + 2.0) / log(2.0) - 1);     long long prevNum = pow(2.0, numPos) - 2;     long long nowNum = k - prevNum;     long long halfNum = pow(2.0, numPos - 1);     string postStr = getKthNum((nowNum > halfNum ? nowNum % halfNum : nowNum) + halfNum - 2);     string prevStr = (nowNum > halfNum) ? "7" : "4";     return prevStr + postStr; } int main() {     int n;     cin >> n;     vector<string> retVec;     while (n--) {         long long k;         cin >> k;                  string ret = getKthNum(k);         retVec.push_back(ret);     }     for (int i = 0; i < retVec.size(); i++) {         cout << retVec[i] << endl;     } return 0; } 从第k个数倒推有多少位,在用递归解
点赞 回复 分享
发布于 2016-09-05 21:23
//题目是不一样的,我是2进制和10进制 import java.util.Scanner; public class Main { public static void main(String args[]) { boolean[] B = new boolean[100000 + 1]; for (int i = 1; i < 100000 + 1; i++) { int binary =g(i); int ten = f(i); if (binary == ten) B[i] = true; } Scanner cin = new Scanner(System.in); int times = cin.nextInt(); for (int i = 0; i < times; i++) { int n = cin.nextInt(); int count = 0; for (int j = 1; j <= n; j++) {{ if (B[j]) count++; } } System.out.println(count); } } private static int f(int num){ String str = String.valueOf(num); int sum = 0; for(int i = str.length() - 1;i>=0;i--){ sum+=Integer.valueOf(str.charAt(i)+""); } return sum; } private static int g(int num){ String str = Integer.toBinaryString(num); int sum = 0; for(int i = 0;i<str.length();i++){ sum+=Integer.valueOf(str.charAt(i)+""); } return sum; } }
点赞 回复 分享
发布于 2016-09-05 21:27

相关推荐

01-24 12:50
门头沟学院 C++
投票
菜狗二号:还有啥想的 指定国有行啊,去了就开始幸福美满的生活了,选华子不是折腾自己么,最终财富积累度是差不多的,但是幸福指数是相差甚远的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务