当前位置: 首页 > news >正文

每日OJ题_牛客_平方数_数学_C++_Java

目录

牛客_平方数_数学

题目解析

C++代码1暴力

C++代码2数学

Java代码数学


牛客_平方数_数学

平方数 (nowcoder.com)

描述:

牛妹是一个喜欢完全平方数的女孩子。
牛妹每次看到一个数 x,都想求出离 x 最近的完全平方数 y。
每次手算太麻烦,所以牛妹希望你能写个程序帮她解决这个问题。
形式化地讲,你需要求出一个正整数 y,满足 y 可以表示成 a^2(a 是正整数),使得 |x-y| 的值最小。可以证明这样的 y 是唯一的。


题目解析

判断一个数开根号之后左右两个数的平方,哪个最近即可。

C++代码1暴力

#include <iostream>
#include <string>
using namespace std;int main()
{string s1, s2;while(cin >> s1 >> s2) // 未知组数的输⼊{int hash[26] = { 0 };for(auto ch : s1) hash[ch - 'A']++;bool ret = true;for(auto ch : s2){if(--hash[ch - 'A'] < 0){ret = false;break;}}cout << (ret ? "Yes" : "No") << endl;}return 0;
}

C++代码2数学

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
#define int long long
signed main()
{int x = 0;cin >> x;int n = sqrt(x);int prev = n * n, next = (n + 1) * (n + 1);if(x - prev < next - x){cout << prev << endl;}else{cout << next << endl;}return 0;
}

Java代码数学

import java.util.*;
public class Main
{public static void main(String[] args){Scanner in = new Scanner(System.in);long x = in.nextLong();long a = (long)Math.sqrt(x);long x1 = a * a, x2 = (a + 1) * (a + 1);if(x - x1 < x2 - x){System.out.println(x1);}else{System.out.println(x2);}}
}

http://www.mrgr.cn/news/45780.html

相关文章:

  • 面试题:Redis(一)
  • 回到原点再出发
  • 职场上的人情世故,你知多少?这五点一定要了解
  • Python获取json返回的字符串获取方法大全
  • 若依初相识
  • 每天一道面试题5——Linux内核包含哪些部分?
  • 【C语言刷力扣】1678.设计Goal解析器
  • Python酷库之旅-第三方库Pandas(137)
  • 解决方案:Pandas里面的loc跟iloc,有什么区别
  • 形式逻辑 | 管理类联考
  • 初入网络学习第一篇
  • Spring Validation —— 参数校验框架
  • 媒界:家庭出行不用愁 江铃集团新能源易至EV3青春版值得拥有
  • C语言基础之结构体
  • 一分钟掌握 Java22 新特性
  • ant-design为input设置默认值,form失效
  • 如何在 MySQL 中处理 BLOB 和 CLOB 数据类型
  • Overleaf 无法显示图片
  • 每日OJ题_牛客_分组_枚举+二分_C++_Java
  • Linux 学习