0
点赞
收藏
分享

微信扫一扫

京东笔试题(JAVA)

树下的老石头 2022-04-05 阅读 48
java

1.一个满二叉树,从1开始编号,你当前在X位置,每一个小时移动一个位置,给你一个字符串s,字符串中的每一个字符代表一种操作,L:向左孩子移动,R:向右孩子移动,U:向父亲移动,求N小时候的位置所在,输入用例形如:N(时间)2当前所在位置

此题需要考虑数值越界问题:

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int n = sc.nextInt();
            //考虑溢出问题,不能用int
            long x = sc.nextInt();
            String s = sc.next();
            //转换为二进制字符串,防止溢出
            //Integer.toBinaryString(int x),Long.toBinaryString(long x)  练习方法,转换为二进制字符串,且构造StringBuilder对象
            StringBuilder str = new StringBuilder(Long.toBinaryString(x));
            for(int i=0;i<n;i++){
                find(str, s.charAt(i));
            }
            //Long.parseLong​(String s,int radix)  Parses the string argument as a signed long in the ‎radix‎ specified by the second argument.
            System.out.println(Long.parseLong(str.toString(),2));
        }
    }
    public static void find(StringBuilder str,char c){
        //向左子节点走,即当前位置乘以2,二进制数左移一位,相当于二进制字符末尾添0
        if(c == 'L'){
            str = str.append('0');
        }else if(c == 'R'){
        //向右子节点走,二进制字符末尾添1
            str = str.append('1');
        }else {
        //向右子节点走,二进制字符串右移一位,删除最后的字符
            str = str.deleteCharAt(str.length() - 1);
        }
    }
}

2.刷油漆,找到使每一行油漆颜色ABC平衡的最少粉刷次数。

输入格式如下:

 统计计数,注意特殊情况。

package com.scu.service.impl;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        for (int i = 0; i < t; i++) {
            int n = sc.nextInt();
            String str = sc.next();
            int result = findCnt(str,n);
            System.out.println(result);
        }
    }
    public static int findCnt(String s,int n){
        char[] tmp = s.toCharArray();
        int[] freq = new int[3];
        //统计三种颜色出现的次数
        for (int i = 0; i < s.length(); i++) {
            freq[tmp[i] - 'A']++;
        }
        //粉刷次数
        int ans = 3;
        for (int j = 0; j < 3; j++) {
            if (freq[j] >= n) {
                ans--;
            }
        }
        //判断特例,没有三个连续的给一起刷,如ABBABBABB
        if(ans == 1) {
            if ((freq[0] == n || freq[1] == n || freq[2] == n)
                && (freq[0] == 0 || freq[1] == 0 || freq[2] == 0)){
                int pre = 0,cnt=0;
                for (int i = 0; i < tmp.length; i++) {
                    if(tmp[i] == tmp[pre]){
                        cnt++;
                    }else{
                        cnt=1;
                        pre = i;
                    }
                    if(cnt == n)break;
                }
                if(cnt < n) ans=2;
            }
        }
        return ans;
    }
}

参考链接 

 

举报

相关推荐

0 条评论