美文网首页程序员
力扣 273 移动零

力扣 273 移动零

作者: zhaojinhui | 来源:发表于2020-08-18 12:14 被阅读0次

题意:给定一个数,把他用英文表示

思路:具体可见代码注释

思想:字符串的处理

复杂度:时间O(n),空间O(n)

class Solution {
    String[] v1 = {"","Thousand", "Million", "Billion"};
    String[] v2 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    String[] v3 = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    public String numberToWords(int num) {
        // num为0
        if(num == 0)
            return "Zero";
        
        String res = "";
        int i = 0;
        // 每次取末尾的3位数,直到num为0
        while(num > 0) {
            int cur = num % 1000;
            num /= 1000;
            // 末尾的3位数不为0
            if(cur != 0) {
                res = get(cur) + " " + v1[i] + " " + res;
            }
            i++;
        }
        // 结果去除空格
        return res.trim();
    }
    // 生成
    String get(int cur) {
        // 获取百位,十位和个位的数字
        int n1 = cur % 10;
        int n2 = cur / 10 % 10;
        int n3 = cur /100 % 10;
        String temp = "";
        // 百位不为0
        if(n3 != 0) {
            temp += v2[n3] + " " + "Hundred";
        }
        // 十位为0
        if(n2 != 0) {
            // 十位如果是1
            if(n2 == 1) {
                temp = temp + " " + v2[cur%100];
                return temp.trim();
            } 
            temp = temp + " " + v3[n2];
        }
        // 个位不为0
        if(n1 != 0) {
            temp = temp + " " + v2[n1];
        }
        // 结果去除空格
        return temp.trim();
    }
}

相关文章

  • 力扣 273 移动零

    题意:给定一个数,把他用英文表示 思路:具体可见代码注释 思想:字符串的处理 复杂度:时间O(n),空间O(n)

  • 新手算法题目

    数组 Array力扣 485最大连续1的个数 | Max Consecutive One力扣 283 移动零 |...

  • 算法:数组(二)

    283. 移动零 - 力扣(LeetCode) (leetcode-cn.com)[https://leetcod...

  • 力扣 283 移动零

    题意:给定一个数组,把其中的0都移动到最后 思路:设一个end指针记录第一个为0的index 遍历数组,把非0的数...

  • 力扣283 - 移动零

    给定一个数组nums,编写一个函数将所有0移动到数组的末尾,同时保持非零元素的相对顺序。 示例:输入: [0,1,...

  • 力扣-283-移动零-双指针

    题目:给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例:输入:...

  • LeetCode 474. 一和零

    1、题目 一和零 - 力扣(LeetCode) https://leetcode-cn.com/problems/...

  • 【力谱云】【app开发制作】移动零售行业解决方案

    【力谱云】【app开发制作https://www.leapcloud.cn】移动零售行业解决方案 ==移动零售单店...

  • 宇宙最冷之地

    回力棒星云是迄今为止人类发现宇宙中最寒冷的地方,温度仅有零下272摄氏度。据理论推算宇宙绝对零度是零下273摄氏度...

  • 力扣73——矩阵置零

    准备开一个力扣解题的系列,督促自己每天刷题,就从今天开始。 原题 给定一个 m x n 的矩阵,如果一个元素为 0...

网友评论

    本文标题:力扣 273 移动零

    本文链接:https://www.haomeiwen.com/subject/eubhjktx.html