华为研发工程师编程题(一)

题一 汽水瓶在这里插入图片描述

1.解法(贪心)
贪心算法,每次使用已有的空瓶数,得到最多数量可以喝的水,接着记录已有的空瓶数,继续算

import java.util.*;

public class Main{
    // 要写在主方法中
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = 0;
        int sum = 0;
       	
        while(sc.hasNext()){
            n = sc.nextInt();
            // 循环结束的条件
            if(n == 0) break; 
            // sum = 0;
            sum = 0;
            while(n > 2){
                sum += (n / 3);
                n = (n % 3) + (n / 3);
            }
            if(n == 2){
                System.out.println(sum+1);
            }else{
                 System.out.println(sum);
            }
        }
    }
}

题二 明明的随机数

在这里插入图片描述

使用的是TreeSet,判断是否有重复的数

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = 0;
        TreeSet<Integer> set = new TreeSet<>();

        while(sc.hasNext()){
            n = sc.nextInt();
            set.clear();

            // 判断n是否>0 抛弃不正确答案
            if(n > 0){
                for(int i = 0; i < n; i++){
                    // 只能加入不重复的数,并且自动有序
                    set.add(sc.nextInt());
                }
            }

            for(Integer i : set){
                System.out.println(i);
            }
        }
    }
}

在这里插入图片描述

题三 进制转换

在这里插入图片描述

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        while (sc.hasNext()){
            StringBuffer sb=new StringBuffer();
            sb.append(sc.next());
            String str=sb.reverse().substring(0,sb.length()-2);
            char ch[]=str.toCharArray();
            int sum=0;
            for(int i=0;i<ch.length;i++){
            // A的ascall码是65
                if(ch[i]>='A'&&ch[i]<='F'){
                    sum+=(Integer.valueOf(ch[i])-55)*Math.pow(16,i);
                }else {
                    sum+=(ch[i] - '0')*Math.pow(16,i);
                }
            }
            System.out.println(sum);
        }
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值