鱼C论坛

 找回密码
 立即注册
查看: 1515|回复: 0

[学习笔记] Google foobar challenge

[复制链接]
发表于 2019-8-12 09:36:42 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
Level 3:

67838013_400022300647778_7341441354863476736_n.png


起初的想法是用dp来解,但是问题来了,input的数可以最多有309位数字,是一个非常大的数,但是一个array 或者 arraylist  的 limits 是 2^31 - 1, 也就是说根本无法储存,所以要引入BigInteger 类来处理此问题。

Here is the solution:
  1. import java.math.BigInteger;

  2. public class main {

  3.     public static void main(String[] args){

  4.         String x = "13";

  5.         BigInteger leng = new BigInteger(x);

  6.         BigInteger one = new BigInteger("1");

  7.         BigInteger _one = new BigInteger("-1");

  8. //        leng = leng.add(_one);

  9. //        System.out.println(leng.toString(2));

  10.         String test = leng.toString(2);

  11. //        System.out.println(leng.toString(2));
  12. //
  13. //        System.out.println(leng.bitLength());

  14.         int count = 0;

  15.         while(leng.bitLength() !=1){

  16.             int lowestSetbit = leng.getLowestSetBit();

  17. //            System.out.println(check_add(leng.toString(2)));

  18.             if(check_add(leng.toString(2))  && leng.bitLength() != 2){

  19. //                System.out.println(1);

  20.                 leng = leng.add(one);

  21.                 count = count + 1 ;


  22.             }

  23.             else{

  24.                 if(lowestSetbit >= 1){

  25.                     count++;

  26.                     leng = leng.shiftRight(1);

  27. //                    System.out.println(leng.toString(2));
  28. //                    System.out.println(lowestSetbit);

  29.                 }
  30.                 else{

  31.                     leng = leng.add(_one);

  32.                     count = count + 1;

  33. //                    System.out.println(leng.toString(2));
  34.                 }
  35.             }
  36.         }

  37.         System.out.println(count);

  38. //        return count;
  39.     }

  40.     private static boolean check_add(String x){

  41.         boolean need_add = true;

  42.         for(int i = 0 ; i < x.length(); i++){

  43. //            System.out.println(x.substring(i,i+1));

  44.             if(Integer.parseInt(x.substring(i,i+1)) != 1){

  45. //                System.out.println("22222");

  46.                 need_add = false;
  47.             }

  48.         }

  49.         return need_add;
  50.     }

  51. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 07:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表